
import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs




class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  def __init__( self			: Optional[int]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: List[Any]=None			,							UpperCamelCase__			: Union[str, Any]=True			,							UpperCamelCase__			: str=None			,							**UpperCamelCase__			: List[Any]    )			->	int:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       config_class
    __magic_name__				     =       has_text_modality
    __magic_name__				     =       kwargs
    __magic_name__				     =       common_properties
  def 							_lowercase							( self			: List[Any]    )			->	str:







    """simple docstring"""






    __magic_name__				     =       self.config_class(**self.inputs_dict    )
    __magic_name__				     =       (
        ["""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:
        __magic_name__				     =       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 							_lowercase							( self			: List[str]    )			->	Any:







    """simple docstring"""






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







    """simple docstring"""






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

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

    self.parent.assertEqual(config_second.to_dict()			,							config_first.to_dict()    )
  def 							_lowercase							( self			: int    )			->	List[str]:







    """simple docstring"""






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

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

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







    """simple docstring"""






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

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

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







    """simple docstring"""






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

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







    """simple docstring"""






    if self.config_class.is_composition:
      return
    __magic_name__				     =       self.config_class()
    self.parent.assertIsNotNone(UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[int]    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       copy.deepcopy(UpperCamelCase__    )
    __magic_name__				     =       self.config_class(**UpperCamelCase__    )
    __magic_name__				     =       []
    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:
      __magic_name__				     =       """\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 							_lowercase							( self			: Optional[int]    )			->	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 math import ceil





def 							SCREAMING_SNAKE_CASE     (			_lowerCamelCase						:       Union[str, Any]			,_lowerCamelCase						:       Union[str, Any]	)       ->      int:
  _lowerCAmelCase						:       Dict  			=     list(range(0			,_lowerCamelCase	)	)

  _lowerCAmelCase						:       Tuple  			=     [item for sublist in list(device_map.values()	) for item in sublist]

  # Duplicate check
  _lowerCAmelCase						:       Union[str, Any]  			=     []
  for i in device_map_blocks:
    if device_map_blocks.count(_lowerCamelCase	) > 1 and i not in duplicate_blocks:
      duplicate_blocks.append(_lowerCamelCase	)
    # Missing blocks
  _lowerCAmelCase						:       int  			=     [i for i in blocks if i not in device_map_blocks]
  _lowerCAmelCase						:       List[Any]  			=     [i for i in device_map_blocks if i not in blocks]

  if len(_lowerCamelCase	) != 0:
    raise ValueError(
        """Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."""
        """ These attention blocks were specified more than once: """ + str(_lowerCamelCase	)	)
  if len(_lowerCamelCase	) != 0:
    raise ValueError(
        """There are attention blocks for this model that are not specified in the device_map. Add these attention """
        """blocks to a device on the device_map: """ + str(_lowerCamelCase	)	)
  if len(_lowerCamelCase	) != 0:
    raise ValueError(
        """The device_map contains more attention blocks than this model has. Remove these from the device_map:"""
        + str(_lowerCamelCase	)	)






def 							SCREAMING_SNAKE_CASE     (			_lowerCamelCase						:       int			,_lowerCamelCase						:       Tuple	)       ->      str:
  _lowerCAmelCase						:       Optional[Any]  			=     list(range(_lowerCamelCase	)	)
  _lowerCAmelCase						:       Optional[Any]  			=     int(ceil(n_layers / len(_lowerCamelCase	)	)	)
  _lowerCAmelCase						:       Optional[int]  			=     [layers[i : i + n_blocks] for i in range(0			,_lowerCamelCase			,_lowerCamelCase	)]

  return dict(zip(_lowerCamelCase			,_lowerCamelCase	)	)




