



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,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_=None,			SCREAMING_SNAKE_CASE_=True,			SCREAMING_SNAKE_CASE_=None,			**SCREAMING_SNAKE_CASE_       )     ->		Dict:
          UpperCamelCase    :  Any							=	parent
          UpperCamelCase    :  Any							=	config_class
          UpperCamelCase    :  Dict							=	has_text_modality
          UpperCamelCase    :  Optional[Any]							=	kwargs
          UpperCamelCase    :  Tuple							=	common_properties
       def 					snake_case_       (			self       )     ->		Tuple:
          UpperCamelCase    :  Optional[int]							=	self.config_class(**self.inputs_dict       )
          UpperCamelCase    :  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(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ),			msg=F"""`{prop}` does not exist"""       )

          # Test that config has the common properties as setter
          for idx, name in enumerate(SCREAMING_SNAKE_CASE_       ):
             try:
                setattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       )
                self.parent.assertEqual(
                    getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ),			SCREAMING_SNAKE_CASE_,			msg=F"""`{name} value {idx} expected, but was {getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       )}"""       )
             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(SCREAMING_SNAKE_CASE_       ):
             try:
                UpperCamelCase    :  int							=	self.config_class(**{name: idx}       )
                self.parent.assertEqual(
                    getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ),			SCREAMING_SNAKE_CASE_,			msg=F"""`{name} value {idx} expected, but was {getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       )}"""       )
             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]:
          UpperCamelCase    :  Optional[int]							=	self.config_class(**self.inputs_dict       )
          UpperCamelCase    :  List[str]							=	json.loads(config.to_json_string()       )
          for key, value in self.inputs_dict.items():
             self.parent.assertEqual(obj[key],			SCREAMING_SNAKE_CASE_       )
       def 					snake_case_       (			self       )     ->		Optional[int]:
          UpperCamelCase    :  Union[str, Any]							=	self.config_class(**self.inputs_dict       )

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

          self.parent.assertEqual(config_second.to_dict(),			config_first.to_dict()       )
       def 					snake_case_       (			self       )     ->		str:
          UpperCamelCase    :  List[Any]							=	self.config_class(**self.inputs_dict       )

          with tempfile.TemporaryDirectory() as tmpdirname:
             config_first.save_pretrained(SCREAMING_SNAKE_CASE_       )
             UpperCamelCase    :  int							=	self.config_class.from_pretrained(SCREAMING_SNAKE_CASE_       )

          self.parent.assertEqual(config_second.to_dict(),			config_first.to_dict()       )
       def 					snake_case_       (			self       )     ->		Union[str, Any]:
          UpperCamelCase    :  Optional[int]							=	self.config_class(**self.inputs_dict       )

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

          self.parent.assertEqual(config_second.to_dict(),			config_first.to_dict()       )
       def 					snake_case_       (			self       )     ->		Union[str, Any]:
          UpperCamelCase    :  Any							=	self.config_class(**self.inputs_dict,			num_labels=5       )
          self.parent.assertEqual(len(config.idalabel       ),			5       )
          self.parent.assertEqual(len(config.labelaid       ),			5       )

          UpperCamelCase    :  str							=	3
          self.parent.assertEqual(len(config.idalabel       ),			3       )
          self.parent.assertEqual(len(config.labelaid       ),			3       )
       def 					snake_case_       (			self       )     ->		str:
          if self.config_class.is_composition:
             return
          UpperCamelCase    :  Tuple							=	self.config_class()
          self.parent.assertIsNotNone(SCREAMING_SNAKE_CASE_       )
       def 					snake_case_       (			self       )     ->		int:
          UpperCamelCase    :  int							=	copy.deepcopy(SCREAMING_SNAKE_CASE_       )
          UpperCamelCase    :  Any							=	self.config_class(**SCREAMING_SNAKE_CASE_       )
          UpperCamelCase    :  List[Any]							=	[]
          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(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ) != value:
                wrong_values.append((key, getattr(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ), value)       )

          if len(SCREAMING_SNAKE_CASE_       ) > 0:
             UpperCamelCase    :  List[Any]							=	'\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       )     ->		Any:
          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()








from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
    from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


__UpperCAmelCase          =       logging.get_logger(__name__)

__UpperCAmelCase          =       {
    '''bigscience/bloom''': '''https://huggingface.co/bigscience/bloom/resolve/main/config.json''',
    '''bigscience/bloom-560m''': '''https://huggingface.co/bigscience/bloom-560m/blob/main/config.json''',
    '''bigscience/bloom-1b1''': '''https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json''',
    '''bigscience/bloom-1b7''': '''https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json''',
    '''bigscience/bloom-3b''': '''https://huggingface.co/bigscience/bloom-3b/blob/main/config.json''',
    '''bigscience/bloom-7b1''': '''https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json''',
}



class 				lowerCAmelCase_		(  a__							):
       UpperCAmelCase__				:					Tuple        =  "bloom"
       UpperCAmelCase__				:					List[Any]        =  ["past_key_values"]
       UpperCAmelCase__				:					str        =  {
           "num_hidden_layers": "n_layer",
           "num_attention_heads": "n_head",
       }
       def __init__(			self,			SCREAMING_SNAKE_CASE_=25_0880,			SCREAMING_SNAKE_CASE_=64,			SCREAMING_SNAKE_CASE_=2,			SCREAMING_SNAKE_CASE_=8,			SCREAMING_SNAKE_CASE_=1e-5,			SCREAMING_SNAKE_CASE_=0.02,			SCREAMING_SNAKE_CASE_=True,			SCREAMING_SNAKE_CASE_=1,			SCREAMING_SNAKE_CASE_=2,			SCREAMING_SNAKE_CASE_=False,			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=1,			SCREAMING_SNAKE_CASE_=False,			**SCREAMING_SNAKE_CASE_,			)     ->		Tuple:
          UpperCamelCase    :  str							=	vocab_size
          # Backward compatibility with n_embed kwarg
          UpperCamelCase    :  Optional[Any]							=	kwargs.pop('n_embed',			SCREAMING_SNAKE_CASE_       )
          UpperCamelCase    :  Union[str, Any]							=	hidden_size if n_embed is None else n_embed
          UpperCamelCase    :  Tuple							=	n_layer
          UpperCamelCase    :  Dict							=	n_head
          UpperCamelCase    :  List[Any]							=	layer_norm_epsilon
          UpperCamelCase    :  Optional[int]							=	initializer_range
          UpperCamelCase    :  int							=	use_cache
          UpperCamelCase    :  int							=	pretraining_tp
          UpperCamelCase    :  Optional[int]							=	apply_residual_connection_post_layernorm
          UpperCamelCase    :  str							=	hidden_dropout
          UpperCamelCase    :  str							=	attention_dropout

          UpperCamelCase    :  List[Any]							=	bos_token_id
          UpperCamelCase    :  Tuple							=	eos_token_id
          UpperCamelCase    :  Union[str, Any]							=	slow_but_exact

          super().__init__(bos_token_id=SCREAMING_SNAKE_CASE_,			eos_token_id=SCREAMING_SNAKE_CASE_,			**SCREAMING_SNAKE_CASE_       )






class 				lowerCAmelCase_		(  a__							):
       UpperCAmelCase__				:					Any        =  version.parse("1.12"							)
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = "default",			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = False,			)     ->		Any:
          super().__init__(SCREAMING_SNAKE_CASE_,			task=SCREAMING_SNAKE_CASE_,			patching_specs=SCREAMING_SNAKE_CASE_,			use_past=SCREAMING_SNAKE_CASE_       )
          if not getattr(self._config,			'pad_token_id',			SCREAMING_SNAKE_CASE_       ):
             # TODO: how to do that better?
             UpperCamelCase    :  Tuple							=	0
       @property
       def 					snake_case_       (			self       )     ->		Mapping[str, Mapping[int, str]]:
          UpperCamelCase    :  str							=	OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}       )
          if self.use_past:
             # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
             self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_,			direction='inputs',			inverted_values_shape=SCREAMING_SNAKE_CASE_       )
             UpperCamelCase    :  Union[str, Any]							=	{0: 'batch', 1: 'past_sequence + sequence'}
          else:
             UpperCamelCase    :  Optional[int]							=	{0: 'batch', 1: 'sequence'}

          return common_inputs
       @property
       def 					snake_case_       (			self       )     ->		int:
          return self._config.n_layer
       @property
       def 					snake_case_       (			self       )     ->		int:
          return self._config.n_head
       @property
       def 					snake_case_       (			self       )     ->		float:
          return 1e-3
       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = -1,			SCREAMING_SNAKE_CASE_ = -1,			SCREAMING_SNAKE_CASE_ = False,			SCREAMING_SNAKE_CASE_ = None,			)     ->		Mapping[str, Any]:
          UpperCamelCase    :  Dict							=	super(SCREAMING_SNAKE_CASE_,			self       ).generate_dummy_inputs(
              SCREAMING_SNAKE_CASE_,			batch_size=SCREAMING_SNAKE_CASE_,			seq_length=SCREAMING_SNAKE_CASE_,			is_pair=SCREAMING_SNAKE_CASE_,			framework=SCREAMING_SNAKE_CASE_       )

          # We need to order the input in the way they appears in the forward()
          UpperCamelCase    :  Any							=	OrderedDict({'input_ids': common_inputs['input_ids']}       )

          # Need to add the past_keys
          if self.use_past:
             if not is_torch_available():
                raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'       )
             else:
                import torch

                UpperCamelCase	,     UpperCamelCase    :  int							=	common_inputs['input_ids'].shape
                # Not using the same length for past_key_values
                UpperCamelCase    :  Any							=	seqlen + 2
                UpperCamelCase    :  Optional[int]							=	self._config.hidden_size // self.num_attention_heads
                UpperCamelCase    :  Any							=	(
                    batch * self.num_attention_heads,
                    head_dim,
                    past_key_values_length,
                )
                UpperCamelCase    :  Optional[Any]							=	(
                    batch * self.num_attention_heads,
                    past_key_values_length,
                    head_dim,
                )
                UpperCamelCase    :  List[str]							=	[
                    (torch.zeros(SCREAMING_SNAKE_CASE_       ), torch.zeros(SCREAMING_SNAKE_CASE_       )) for _ in range(self.num_layers       )
                ]

          UpperCamelCase    :  str							=	common_inputs['attention_mask']
          if self.use_past:
             UpperCamelCase    :  int							=	ordered_inputs['attention_mask'].dtype
             UpperCamelCase    :  List[Any]							=	torch.cat(
                 [ordered_inputs['attention_mask'], torch.ones(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			dtype=SCREAMING_SNAKE_CASE_       )],			dim=1       )

          return ordered_inputs






       @property
       def 					snake_case_       (			self       )     ->		int:
          return 13



