


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,      lowerCamelCase,      lowerCamelCase=None,      lowerCamelCase=True,      lowerCamelCase=None,      **lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							Dict      		=		parent
           _lowercase       :							List[Any]      		=		config_class
           _lowercase       :							List[Any]      		=		has_text_modality
           _lowercase       :							str      		=		kwargs
           _lowercase       :							Union[str, Any]      		=		common_properties
       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							int      		=		self.config_class(**self.inputs_dict)
           _lowercase       :							Union[str, Any]      		=		(
               ['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(__UpperCAmelCase,      __UpperCAmelCase),      msg=F'''`{prop}` does not exist''')

           # Test that config has the common properties as setter
           for idx, name in enumerate(__UpperCAmelCase):
               try:
                   setattr(__UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase)
                   self.parent.assertEqual(
                       getattr(__UpperCAmelCase,      __UpperCAmelCase),      __UpperCAmelCase,      msg=F'''`{name} value {idx} expected, but was {getattr(__UpperCAmelCase,      __UpperCAmelCase)}''')
               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(__UpperCAmelCase):
               try:
                   _lowercase       :							Any      		=		self.config_class(**{name: idx})
                   self.parent.assertEqual(
                       getattr(__UpperCAmelCase,      __UpperCAmelCase),      __UpperCAmelCase,      msg=F'''`{name} value {idx} expected, but was {getattr(__UpperCAmelCase,      __UpperCAmelCase)}''')
               except NotImplementedError:
                   # Some models might not be able to implement setters for common_properties
                   # In that case, a NotImplementedError is raised
                   pass
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		self.config_class(**self.inputs_dict)
           _lowercase       :							Tuple      		=		json.loads(config.to_json_string())
           for key, value in self.inputs_dict.items():
               self.parent.assertEqual(obj[key],      __UpperCAmelCase)
       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Any      		=		self.config_class(**self.inputs_dict)

           with tempfile.TemporaryDirectory() as tmpdirname:
               _lowercase       :							Optional[Any]      		=		os.path.join(__UpperCAmelCase,      'config.json')
               config_first.to_json_file(__UpperCAmelCase)
               _lowercase       :							int      		=		self.config_class.from_json_file(__UpperCAmelCase)

           self.parent.assertEqual(config_second.to_dict(),      config_first.to_dict())
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		self.config_class(**self.inputs_dict)

           with tempfile.TemporaryDirectory() as tmpdirname:
               config_first.save_pretrained(__UpperCAmelCase)
               _lowercase       :							str      		=		self.config_class.from_pretrained(__UpperCAmelCase)

           self.parent.assertEqual(config_second.to_dict(),      config_first.to_dict())
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							int      		=		self.config_class(**self.inputs_dict)

           _lowercase       :							List[Any]      		=		'test'
           with tempfile.TemporaryDirectory() as tmpdirname:
               _lowercase       :							Tuple      		=		os.path.join(__UpperCAmelCase,      __UpperCAmelCase)
               config_first.save_pretrained(__UpperCAmelCase)
               _lowercase       :							Optional[int]      		=		self.config_class.from_pretrained(__UpperCAmelCase,      subfolder=__UpperCAmelCase)

           self.parent.assertEqual(config_second.to_dict(),      config_first.to_dict())
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

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

           _lowercase       :							Any      		=		3
           self.parent.assertEqual(len(config.idalabel),      3)
           self.parent.assertEqual(len(config.labelaid),      3)
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           if self.config_class.is_composition:
               return
           _lowercase       :							List[Any]      		=		self.config_class()
           self.parent.assertIsNotNone(__UpperCAmelCase)
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		copy.deepcopy(__UpperCAmelCase)
           _lowercase       :							Tuple      		=		self.config_class(**__UpperCAmelCase)
           _lowercase       :							int      		=		[]
           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(__UpperCAmelCase,      __UpperCAmelCase) != value:
                   wrong_values.append((key, getattr(__UpperCAmelCase,      __UpperCAmelCase), value))

           if len(__UpperCAmelCase) > 0:
               _lowercase       :							List[str]      		=		'\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 			UpperCamelCase     (					self)       ->   List[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 collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar

__A											=		TypeVar("""KEY""")
__A											=		TypeVar("""VAL""")






@dataclass(frozen=a  ,   slots=a       )
class 					_lowerCAmelCase   (     Generic[KEY, VAL]       ):
       """simple docstring"""




       __magic_name__     :KEY
       __magic_name__     :VAL






class 					_lowerCAmelCase   (     _Item       ):
       """simple docstring"""




       def __init__(    self      ):



         '''simple docstring'''

         super().__init__(__UpperCAmelCase    , __UpperCAmelCase      )






       def __bool__(    self      ):



         '''simple docstring'''

         return False






__A											=		_DeletedItem()






class 					_lowerCAmelCase   (     MutableMapping[KEY, VAL]       ):
       """simple docstring"""




       def __init__(    self    , __UpperCAmelCase = 8    , __UpperCAmelCase = 0.75      ):



         '''simple docstring'''

         lowerCAmelCase__			:List[str]											=							initial_block_size
         lowerCAmelCase__			:list[_Item | None]											=							[None] * initial_block_size
         assert 0.0 < capacity_factor < 1.0
         lowerCAmelCase__			:Tuple											=							capacity_factor
         lowerCAmelCase__			:str											=							0






       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         return hash(__UpperCAmelCase      ) % len(self._buckets      )






       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         return (ind + 1) % len(self._buckets      )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Any											=							self._buckets[ind]
         if not stored:
           lowerCAmelCase__			:Dict											=							_Item(__UpperCAmelCase    , __UpperCAmelCase      )
           self._len += 1
           return True
         elif stored.key == key:
           lowerCAmelCase__			:Optional[Any]											=							_Item(__UpperCAmelCase    , __UpperCAmelCase      )
           return True
         else:
           return False






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:int											=							len(self._buckets      ) * self._capacity_factor
         return len(self      ) >= int(__UpperCAmelCase      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         if len(self._buckets      ) <= self._initial_block_size:
           return False
         lowerCAmelCase__			:Optional[Any]											=							len(self._buckets      ) * self._capacity_factor / 2
         return len(self      ) < limit






       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[int]											=							self._buckets
         lowerCAmelCase__			:Tuple											=							[None] * new_size
         lowerCAmelCase__			:List[Any]											=							0
         for item in old_buckets:
           if item:
             self._add_item(item.key    , item.val      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         self._resize(len(self._buckets      ) * 2      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         self._resize(len(self._buckets      ) // 2      )






       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[Any]											=							self._get_bucket_index(__UpperCAmelCase      )
         for _ in range(len(self._buckets      )      ):
           yield ind
           lowerCAmelCase__			:Tuple											=							self._get_next_ind(__UpperCAmelCase      )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase      ):



         '''simple docstring'''

         for ind in self._iterate_buckets(__UpperCAmelCase      ):
           if self._try_set(__UpperCAmelCase    , __UpperCAmelCase    , __UpperCAmelCase      ):
             break






       def __setitem__(    self    , __UpperCAmelCase    , __UpperCAmelCase      ):



         '''simple docstring'''

         if self._is_full():
           self._size_up()

         self._add_item(__UpperCAmelCase    , __UpperCAmelCase      )






       def __delitem__(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         for ind in self._iterate_buckets(__UpperCAmelCase      ):
           lowerCAmelCase__			:int											=							self._buckets[ind]
           if item is None:
             raise KeyError(__UpperCAmelCase      )
           if item is _deleted:
             continue
           if item.key == key:
             lowerCAmelCase__			:List[str]											=							_deleted
             self._len -= 1
             break
         if self._is_sparse():
           self._size_down()






       def __getitem__(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         for ind in self._iterate_buckets(__UpperCAmelCase      ):
           lowerCAmelCase__			:str											=							self._buckets[ind]
           if item is None:
             break
           if item is _deleted:
             continue
           if item.key == key:
             return item.val
         raise KeyError(__UpperCAmelCase      )






       def __len__(    self      ):



         '''simple docstring'''

         return self._len






       def __iter__(    self      ):



         '''simple docstring'''

         yield from (item.key for item in self._buckets if item)






       def __repr__(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Tuple											=							' ,'.join(
             F"{item.key}: {item.val}" for item in self._buckets if item      )
         return F"HashMap({val_string})"
