



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__snake_case		:Any   	=  logging.get_logger(__name__)

__snake_case		:Optional[int]   	=  {
    '''google/pix2struct-textcaps-base''': (
        '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json'''
    ),
}

class 					_A (			__UpperCAmelCase					):
       UpperCamelCase__						:					Dict		      =		'''pix2struct_text_model'''
       UpperCamelCase__						:					int		      =		['''past_key_values''']
       UpperCamelCase__						:					Dict		      =		{
           '''hidden_size''': '''hidden_size''',
           '''num_attention_heads''': '''num_heads''',
           '''num_hidden_layers''': '''num_layers''',
       }



       def __init__(	self							:  List[str]  ,	__SCREAMING_SNAKE_CASE							:  Dict=50_244  ,	__SCREAMING_SNAKE_CASE							:  List[str]=768  ,	__SCREAMING_SNAKE_CASE							:  Any=64  ,	__SCREAMING_SNAKE_CASE							:  str=2_048  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=12  ,	__SCREAMING_SNAKE_CASE							:  Tuple=12  ,	__SCREAMING_SNAKE_CASE							:  Any=32  ,	__SCREAMING_SNAKE_CASE							:  str=128  ,	__SCREAMING_SNAKE_CASE							:  int=0.1  ,	__SCREAMING_SNAKE_CASE							:  Dict=1E-6  ,	__SCREAMING_SNAKE_CASE							:  str=1.0  ,	__SCREAMING_SNAKE_CASE							:  int="gelu_new"  ,	__SCREAMING_SNAKE_CASE							:  Tuple=0  ,	__SCREAMING_SNAKE_CASE							:  int=False  ,	__SCREAMING_SNAKE_CASE							:  Any=0  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=1  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=False  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=True  ,	**__SCREAMING_SNAKE_CASE							:  str  ,	):


           '''simple docstring'''

           __a		 =       vocab_size
           __a		 =       hidden_size
           __a		 =       d_kv
           __a		 =       d_ff
           __a		 =       num_layers
           __a		 =       num_heads
           __a		 =       relative_attention_num_buckets
           __a		 =       relative_attention_max_distance
           __a		 =       dropout_rate
           __a		 =       layer_norm_epsilon
           __a		 =       initializer_factor
           __a		 =       use_cache

           __a		 =       eos_token_id
           __a		 =       decoder_start_token_id

           # for backwards compatibility
           __a		 =       dense_act_fn

           super().__init__(
               pad_token_id=__SCREAMING_SNAKE_CASE  ,	eos_token_id=__SCREAMING_SNAKE_CASE  ,	decoder_start_token_id=__SCREAMING_SNAKE_CASE  ,	tie_word_embeddings=__SCREAMING_SNAKE_CASE  ,	is_decoder=__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE  ,	)





       @classmethod
       def 	_lowerCamelCase    (	cls							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  Union[str, os.PathLike]  ,	**__SCREAMING_SNAKE_CASE							:  Dict):


           '''simple docstring'''

           cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE)

           __a ,     __a		 =       cls.get_config_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           # get the text config dict if we are loading from Pix2StructConfig
           if config_dict.get('''model_type''') == "pix2struct":
               __a		 =       config_dict['''text_config''']

           if "model_type" in config_dict and hasattr(cls  ,	'''model_type''') and config_dict["model_type"] != cls.model_type:
               logger.warning(
                   F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                   F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.')

           return cls.from_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)


class 					_A (			__UpperCAmelCase					):
       UpperCamelCase__						:					Optional[int]		      =		'''pix2struct_vision_model'''



       def __init__(	self							:  List[str]  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=768  ,	__SCREAMING_SNAKE_CASE							:  int=768  ,	__SCREAMING_SNAKE_CASE							:  Tuple=2_048  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=64  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=12  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=12  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]="gelu_new"  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=1E-6  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=0.0  ,	__SCREAMING_SNAKE_CASE							:  int=0.0  ,	__SCREAMING_SNAKE_CASE							:  Tuple=1E-10  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=1.0  ,	__SCREAMING_SNAKE_CASE							:  Dict=4_096  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]=32  ,	__SCREAMING_SNAKE_CASE							:  Tuple=128  ,	**__SCREAMING_SNAKE_CASE							:  Tuple  ,	):


           '''simple docstring'''

           super().__init__(**__SCREAMING_SNAKE_CASE)

           __a		 =       hidden_size
           __a		 =       patch_embed_hidden_size
           __a		 =       d_ff
           __a		 =       dropout_rate
           __a		 =       num_hidden_layers
           __a		 =       num_attention_heads
           __a		 =       initializer_range
           __a		 =       initializer_factor
           __a		 =       attention_dropout
           __a		 =       layer_norm_eps
           __a		 =       dense_act_fn
           __a		 =       seq_len
           __a		 =       relative_attention_num_buckets
           __a		 =       relative_attention_max_distance
           __a		 =       d_kv





       @classmethod
       def 	_lowerCamelCase    (	cls							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  Union[str, os.PathLike]  ,	**__SCREAMING_SNAKE_CASE							:  Union[str, Any]):


           '''simple docstring'''

           cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE)

           __a ,     __a		 =       cls.get_config_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           # get the vision config dict if we are loading from Pix2StructConfig
           if config_dict.get('''model_type''') == "pix2struct":
               __a		 =       config_dict['''vision_config''']

           if "model_type" in config_dict and hasattr(cls  ,	'''model_type''') and config_dict["model_type"] != cls.model_type:
               logger.warning(
                   F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                   F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.')

           return cls.from_dict(__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)


class 					_A (			__UpperCAmelCase					):
       UpperCamelCase__						:					Dict		      =		'''pix2struct'''
       UpperCamelCase__						:					Union[str, Any]		      =		True



       def __init__(	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  List[str]=None  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=None  ,	__SCREAMING_SNAKE_CASE							:  Tuple=1.0  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=0.02  ,	__SCREAMING_SNAKE_CASE							:  int=False  ,	__SCREAMING_SNAKE_CASE							:  Tuple=False  ,	__SCREAMING_SNAKE_CASE							:  List[str]=True  ,	**__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	):


           '''simple docstring'''

           super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE  ,	is_encoder_decoder=__SCREAMING_SNAKE_CASE  ,	**__SCREAMING_SNAKE_CASE)

           if text_config is None:
               __a		 =       {}
               logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''')

           if vision_config is None:
               __a		 =       {}
               logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''')

           __a		 =       PixaStructTextConfig(**__SCREAMING_SNAKE_CASE)
           __a		 =       PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE)

           __a		 =       self.text_config.decoder_start_token_id
           __a		 =       self.text_config.pad_token_id
           __a		 =       self.text_config.eos_token_id

           __a		 =       initializer_factor
           __a		 =       initializer_range

           __a		 =       self.initializer_range
           __a		 =       self.initializer_range

           __a		 =       is_vqa



       @classmethod
       def 	_lowerCamelCase    (	cls							:  Any  ,	__SCREAMING_SNAKE_CASE							:  PixaStructTextConfig  ,	__SCREAMING_SNAKE_CASE							:  PixaStructVisionConfig  ,	**__SCREAMING_SNAKE_CASE							:  Optional[int]):


           '''simple docstring'''

           return cls(text_config=text_config.to_dict()  ,	vision_config=vision_config.to_dict()  ,	**__SCREAMING_SNAKE_CASE)





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


           '''simple docstring'''

           __a		 =       copy.deepcopy(self.__dict__)
           __a		 =       self.text_config.to_dict()
           __a		 =       self.vision_config.to_dict()
           __a		 =       self.__class__.model_type
           return output










import os
import sys
import unittest


__snake_case		:Union[str, Any]   	=  os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__snake_case		:List[str]   	=  os.path.join(git_repo_path, '''src''', '''transformers''')

__snake_case		:Any   	=  '''
{0} = None
'''

__snake_case		:Dict   	=  '''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__snake_case		:str   	=  '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''

class 					_A (			unittest.TestCase					):



       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           __a		 =       find_backend('''    _import_structure["models.albert"].append("AlbertTokenizerFast")''')
           self.assertIsNone(__SCREAMING_SNAKE_CASE)

           __a		 =       find_backend('''    if not is_tokenizers_available():''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''tokenizers''')

           __a		 =       find_backend('''    if not is_tensorflow_text_available():''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''tensorflow_text''')

           __a		 =       find_backend('''    if not (is_sentencepiece_available() and is_tokenizers_available()):''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''sentencepiece_and_tokenizers''')

           __a		 =       find_backend(
               '''    if not (is_sentencepiece_available() and is_tensorflow_text_available()):''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''sentencepiece_and_tensorflow_text''')

           __a		 =       find_backend(
               '''    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''sentencepiece_and_tokenizers_and_vision''')



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           __a		 =       read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn('''torch'''  ,	__SCREAMING_SNAKE_CASE)
           self.assertIn('''tensorflow_text'''  ,	__SCREAMING_SNAKE_CASE)
           self.assertIn('''sentencepiece_and_tokenizers'''  ,	__SCREAMING_SNAKE_CASE)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn('''BertModel'''  ,	objects['''torch'''])
           self.assertIn('''TFBertModel'''  ,	objects['''tf'''])
           self.assertIn('''FlaxBertModel'''  ,	objects['''flax'''])
           self.assertIn('''BertModel'''  ,	objects['''torch'''])
           self.assertIn('''TFBertTokenizer'''  ,	objects['''tensorflow_text'''])
           self.assertIn('''convert_slow_tokenizer'''  ,	objects['''sentencepiece_and_tokenizers'''])



       def 	_lowerCamelCase    (	self							:  Any):


           '''simple docstring'''

           __a		 =       create_dummy_object('''CONSTANT'''  ,	'''\'torch\'''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''\nCONSTANT = None\n''')

           __a		 =       create_dummy_object('''function'''  ,	'''\'torch\'''')
           self.assertEqual(
               __SCREAMING_SNAKE_CASE  ,	'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n''')

           __a		 =       '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')
'''
           __a		 =       create_dummy_object('''FakeClass'''  ,	'''\'torch\'''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)





       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           __a		 =       '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, ["torch"])


class FakeClass(metaclass=DummyObject):
    _backends = ["torch"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, ["torch"])
'''
           __a		 =       create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']})
           self.assertEqual(dummy_files['''torch''']  ,	__SCREAMING_SNAKE_CASE)





