





import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
      from ... import PreTrainedTokenizerBase, TensorType

snake_case								=							logging.get_logger(__name__)





class 					A_					(   UpperCAmelCase						):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_   :			Dict  			=	'''vision-encoder-decoder'''
       SCREAMING_SNAKE_CASE_   :			Any  			=	True







       def __init__(     self						:						List[Any]    ,**__A						:						List[str]	)    ->       Optional[Any]:
         super().__init__(**__A	)
         if "encoder" not in kwargs or "decoder" not in kwargs:
           raise ValueError(
               F"""A configuraton of type {self.model_type} cannot be instantiated because """
               F"""not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}"""	)

         _lowercase						    =			kwargs.pop('encoder'	)
         _lowercase						    =			encoder_config.pop('model_type'	)
         _lowercase						    =			kwargs.pop('decoder'	)
         _lowercase						    =			decoder_config.pop('model_type'	)

         _lowercase						    =			AutoConfig.for_model(__A    ,**__A	)
         _lowercase						    =			AutoConfig.for_model(__A    ,**__A	)
         _lowercase						    =			True







       @classmethod
       def  __UpperCAmelCase			(     cls						:						Any    ,__A						:						PretrainedConfig    ,__A						:						PretrainedConfig    ,**__A						:						List[str]	)    ->       PretrainedConfig:
         logger.info('Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'	)
         _lowercase						    =			True
         _lowercase						    =			True

         return cls(encoder=encoder_config.to_dict()    ,decoder=decoder_config.to_dict()    ,**__A	)







       def  __UpperCAmelCase			(     self						:						Union[str, Any]	)    ->       List[Any]:
         _lowercase						    =			copy.deepcopy(self.__dict__	)
         _lowercase						    =			self.encoder.to_dict()
         _lowercase						    =			self.decoder.to_dict()
         _lowercase						    =			self.__class__.model_type
         return output





class 					A_					(   UpperCAmelCase						):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_   :			Union[str, Any]  			=	version.parse('''1.11'''						)







       @property
       def  __UpperCAmelCase			(     self						:						Optional[Any]	)    ->       Mapping[str, Mapping[int, str]]:
         return OrderedDict(
             [
                 ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
             ]	)







       @property
       def  __UpperCAmelCase			(     self						:						int	)    ->       float:
         return 1e-4







       @property
       def  __UpperCAmelCase			(     self						:						str	)    ->       Mapping[str, Mapping[int, str]]:
         return OrderedDict({'last_hidden_state': {0: 'batch', 1: 'encoder_sequence'}}	)





class 					A_					(   UpperCAmelCase						):







       """simple docstring"""





       @property
       def  __UpperCAmelCase			(     self						:						Optional[Any]	)    ->       Mapping[str, Mapping[int, str]]:
         _lowercase						    =			OrderedDict()
         _lowercase						    =			{0: 'batch', 1: 'past_decoder_sequence + sequence'}
         _lowercase						    =			{0: 'batch', 1: 'past_decoder_sequence + sequence'}
         _lowercase						    =			{0: 'batch', 1: 'encoder_sequence'}

         return common_inputs







       def  __UpperCAmelCase			(     self						:						List[str]    ,__A						:						"PreTrainedTokenizerBase"    ,__A						:						int = -1    ,__A						:						int = -1    ,__A						:						bool = False    ,__A						:						Optional["TensorType"] = None    ,)    ->       Mapping[str, Any]:
         import torch

         _lowercase						    =			OrderedDict()

         _lowercase						    =			super().generate_dummy_inputs(
             __A    ,batch_size=__A    ,seq_length=__A    ,is_pair=__A    ,framework=__A	)

         _lowercase    ,		_lowercase						    =			dummy_input['input_ids'].shape
         _lowercase						    =			(batch, encoder_sequence, self._config.encoder_hidden_size)
         _lowercase						    =			dummy_input.pop('input_ids'	)
         _lowercase						    =			dummy_input.pop('attention_mask'	)
         _lowercase						    =			torch.zeros(__A	)

         return common_inputs





class 					A_					(   UpperCAmelCase						):







       """simple docstring"""





       @property
       def  __UpperCAmelCase			(     self						:						List[str]	)    ->       None:
         pass







       def  __UpperCAmelCase			(     self						:						List[str]    ,__A						:						PretrainedConfig	)    ->       OnnxConfig:
         return VisionEncoderDecoderEncoderOnnxConfig(__A	)







       def  __UpperCAmelCase			(     self						:						Dict    ,__A						:						PretrainedConfig    ,__A						:						PretrainedConfig    ,__A						:						str = "default"	)    ->       OnnxConfig:
         _lowercase						    =			encoder_config.hidden_size
         return VisionEncoderDecoderDecoderOnnxConfig(__A    ,__A	)





import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402


a__		     =     get_tests_dir('''fixtures/dummy-config.json''')


class    SCREAMING_SNAKE_CASE_				(       unittest.TestCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						str	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[Any]             =      0






	def 					lowerCamelCase__     (					self		:						Union[str, Any]	)	->       List[str]:







						"""simple docstring"""







						self.assertIsNotNone(transformers.models.auto.__spec__	)
						self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto"""	)	)






	def 					lowerCamelCase__     (					self		:						Optional[Any]	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	int             =      AutoConfig.from_pretrained("""bert-base-uncased"""	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						List[Any]	)	->       Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Dict             =      AutoConfig.from_pretrained(lowerCAmelCase	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Any	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[int]             =      AutoConfig.from_pretrained(lowerCAmelCase	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       Any:







						"""simple docstring"""







						__UpperCamelCase					:	List[Any]             =      AutoConfig.for_model("""roberta"""	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						int	)	->       List[Any]:







						"""simple docstring"""







						with tempfile.TemporaryDirectory() as tmp_dir:
											# This model name contains bert and roberta, but roberta ends up being picked.
											__UpperCamelCase					:	Union[str, Any]             =      os.path.join(lowerCAmelCase					,     """fake-roberta"""	)
											os.makedirs(lowerCAmelCase					,     exist_ok=lowerCAmelCase	)
											with open(os.path.join(lowerCAmelCase					,     """config.json"""	)					,     """w"""	) as f:
																f.write(json.dumps({}	)	)
											__UpperCamelCase					:	Dict             =      AutoConfig.from_pretrained(lowerCAmelCase	)
											self.assertEqual(type(lowerCAmelCase	)					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						int	)	->       str:







						"""simple docstring"""







						try:
											AutoConfig.register("""custom"""					,     lowerCAmelCase	)
											# Wrong model type will raise an error
											with self.assertRaises(lowerCAmelCase	):
																AutoConfig.register("""model"""					,     lowerCAmelCase	)
											# Trying to register something existing in the Transformers library will raise an error
											with self.assertRaises(lowerCAmelCase	):
																AutoConfig.register("""bert"""					,     lowerCAmelCase	)

											# Now that the config is registered, it can be used as any other config with the auto-API
											__UpperCamelCase					:	Optional[Any]             =      CustomConfig()
											with tempfile.TemporaryDirectory() as tmp_dir:
																config.save_pretrained(lowerCAmelCase	)
																__UpperCamelCase					:	List[str]             =      AutoConfig.from_pretrained(lowerCAmelCase	)
																self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)

						finally:
											if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]






	def 					lowerCamelCase__     (					self		:						int	)	->       Optional[Any]:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     """bert-base is not a local folder and is not a valid model identifier"""	):
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""bert-base"""	)






	def 					lowerCamelCase__     (					self		:						Dict	)	->       Any:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""	):
											__UpperCamelCase					:	Optional[Any]             =      AutoConfig.from_pretrained(lowerCAmelCase					,     revision="""aaaaaa"""	)






	def 					lowerCamelCase__     (					self		:						str	)	->       List[str]:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     """hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."""					,     ):
											__UpperCamelCase					:	Union[str, Any]             =      AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo"""	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       Optional[int]:







						"""simple docstring"""







						with self.assertRaises(lowerCAmelCase	):
											__UpperCamelCase					:	str             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""	)
						# If remote code is disabled, we can't load this config.
						with self.assertRaises(lowerCAmelCase	):
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)

						__UpperCamelCase					:	List[str]             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
						self.assertEqual(config.__class__.__name__					,     """NewModelConfig"""	)

						# Test config can be reloaded.
						with tempfile.TemporaryDirectory() as tmp_dir:
											config.save_pretrained(lowerCAmelCase	)
											__UpperCamelCase					:	str             =      AutoConfig.from_pretrained(lowerCAmelCase					,     trust_remote_code=lowerCAmelCase	)
						self.assertEqual(reloaded_config.__class__.__name__					,     """NewModelConfig"""	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       str:







						"""simple docstring"""







						class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



							"""simple docstring"""


							__magic_name__   :       int      	=		'new-model'

						try:
											AutoConfig.register("""new-model"""					,     lowerCAmelCase	)
											# If remote code is not set, the default is to use local
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfigLocal"""	)

											# If remote code is disabled, we load the local one.
											__UpperCamelCase					:	Any             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfigLocal"""	)

											# If remote is enabled, we load from the Hub
											__UpperCamelCase					:	List[Any]             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfig"""	)

						finally:
											if "new-model" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["new-model"]






