
import copy
import os
from typing import Union

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


__UpperCAmelCase							=			logging.get_logger(__name__)

__UpperCAmelCase							=			{
    "google/pix2struct-textcaps-base": (
        "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"
    ),
}





class 							UpperCamelCase__						(     SCREAMING_SNAKE_CASE_     ):






       """simple docstring"""


       UpperCAmelCase_							    ='''pix2struct_text_model'''
       UpperCAmelCase_							    =['''past_key_values''']
       UpperCAmelCase_							    ={
           '''hidden_size''': '''hidden_size''',
           '''num_attention_heads''': '''num_heads''',
           '''num_hidden_layers''': '''num_layers''',
       }



       def __init__(				self      ,			_A=50244      ,			_A=768      ,			_A=64      ,			_A=2048      ,			_A=12      ,			_A=12      ,			_A=32      ,			_A=128      ,			_A=0.1      ,			_A=1E-6      ,			_A=1.0      ,			_A="gelu_new"      ,			_A=0      ,			_A=False      ,			_A=0      ,			_A=1      ,			_A=False      ,			_A=True      ,			**_A      ,			)							->							Tuple:
          SCREAMING_SNAKE_CASE_     =	vocab_size
          SCREAMING_SNAKE_CASE_     =	hidden_size
          SCREAMING_SNAKE_CASE_     =	d_kv
          SCREAMING_SNAKE_CASE_     =	d_ff
          SCREAMING_SNAKE_CASE_     =	num_layers
          SCREAMING_SNAKE_CASE_     =	num_heads
          SCREAMING_SNAKE_CASE_     =	relative_attention_num_buckets
          SCREAMING_SNAKE_CASE_     =	relative_attention_max_distance
          SCREAMING_SNAKE_CASE_     =	dropout_rate
          SCREAMING_SNAKE_CASE_     =	layer_norm_epsilon
          SCREAMING_SNAKE_CASE_     =	initializer_factor
          SCREAMING_SNAKE_CASE_     =	use_cache

          SCREAMING_SNAKE_CASE_     =	eos_token_id
          SCREAMING_SNAKE_CASE_     =	decoder_start_token_id

          # for backwards compatibility
          SCREAMING_SNAKE_CASE_     =	dense_act_fn

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




       @classmethod
       def   _UpperCamelCase     (				cls      ,			_A      ,			**_A     )							->							"PretrainedConfig":
          cls._set_token_in_kwargs(__UpperCAmelCase     )

          SCREAMING_SNAKE_CASE_     =	cls.get_config_dict(__UpperCAmelCase      ,			**__UpperCAmelCase     )

          # get the text config dict if we are loading from Pix2StructConfig
          if config_dict.get('''model_type'''     ) == "pix2struct":
             SCREAMING_SNAKE_CASE_     =	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(__UpperCAmelCase      ,			**__UpperCAmelCase     )







class 							UpperCamelCase__						(     SCREAMING_SNAKE_CASE_     ):






       """simple docstring"""


       UpperCAmelCase_							    ='''pix2struct_vision_model'''



       def __init__(				self      ,			_A=768      ,			_A=768      ,			_A=2048      ,			_A=64      ,			_A=12      ,			_A=12      ,			_A="gelu_new"      ,			_A=1E-6      ,			_A=0.0      ,			_A=0.0      ,			_A=1E-10      ,			_A=1.0      ,			_A=4096      ,			_A=32      ,			_A=128      ,			**_A      ,			)							->							Union[str, Any]:
          super().__init__(**__UpperCAmelCase     )

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




       @classmethod
       def   _UpperCamelCase     (				cls      ,			_A      ,			**_A     )							->							"PretrainedConfig":
          cls._set_token_in_kwargs(__UpperCAmelCase     )

          SCREAMING_SNAKE_CASE_     =	cls.get_config_dict(__UpperCAmelCase      ,			**__UpperCAmelCase     )

          # get the vision config dict if we are loading from Pix2StructConfig
          if config_dict.get('''model_type'''     ) == "pix2struct":
             SCREAMING_SNAKE_CASE_     =	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(__UpperCAmelCase      ,			**__UpperCAmelCase     )







class 							UpperCamelCase__						(     SCREAMING_SNAKE_CASE_     ):






       """simple docstring"""


       UpperCAmelCase_							    ='''pix2struct'''
       UpperCAmelCase_							    =True



       def __init__(				self      ,			_A=None      ,			_A=None      ,			_A=1.0      ,			_A=0.02      ,			_A=False      ,			_A=False      ,			_A=True      ,			**_A      ,			)							->							Tuple:
          super().__init__(tie_word_embeddings=__UpperCAmelCase      ,			is_encoder_decoder=__UpperCAmelCase      ,			**__UpperCAmelCase     )

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

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

          SCREAMING_SNAKE_CASE_     =	PixaStructTextConfig(**__UpperCAmelCase     )
          SCREAMING_SNAKE_CASE_     =	PixaStructVisionConfig(**__UpperCAmelCase     )

          SCREAMING_SNAKE_CASE_     =	self.text_config.decoder_start_token_id
          SCREAMING_SNAKE_CASE_     =	self.text_config.pad_token_id
          SCREAMING_SNAKE_CASE_     =	self.text_config.eos_token_id

          SCREAMING_SNAKE_CASE_     =	initializer_factor
          SCREAMING_SNAKE_CASE_     =	initializer_range

          SCREAMING_SNAKE_CASE_     =	self.initializer_range
          SCREAMING_SNAKE_CASE_     =	self.initializer_range

          SCREAMING_SNAKE_CASE_     =	is_vqa



       @classmethod
       def   _UpperCamelCase     (				cls      ,			_A      ,			_A      ,			**_A     )							->							Optional[int]:
          return cls(text_config=text_config.to_dict()      ,			vision_config=vision_config.to_dict()      ,			**__UpperCAmelCase     )




       def   _UpperCamelCase     (				self     )							->							str:
          SCREAMING_SNAKE_CASE_     =	copy.deepcopy(self.__dict__     )
          SCREAMING_SNAKE_CASE_     =	self.text_config.to_dict()
          SCREAMING_SNAKE_CASE_     =	self.vision_config.to_dict()
          SCREAMING_SNAKE_CASE_     =	self.__class__.model_type
          return output







'''simple docstring'''





def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    lowerCAmelCase__ :  Tuple							      =					abs(UpperCamelCase			)
    lowerCAmelCase__ :  List[Any]							      =					0
    while n > 0:
        res += n % 10
        n //= 10
    return res
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    lowerCAmelCase__ :  Union[str, Any]							      =					abs(UpperCamelCase			)
    return n if n < 10 else n % 10 + sum_of_digits(n // 10			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return sum(int(UpperCamelCase			) for c in str(abs(UpperCamelCase			)			)			)
def    _SCREAMING_SNAKE_CASE  (       ):



    """simple docstring"""





    from collections.abc import Callable
    from timeit import timeit

    def benchmark_a_function(UpperCamelCase							,    UpperCamelCase			) -> None:
        lowerCAmelCase__ :  str							      =					f"""{func.__name__}({value})"""
        lowerCAmelCase__ :  str							      =					timeit(f"""__main__.{call}"""							,    setup="""import __main__"""			)
        print(f"""{call:56} = {func(UpperCamelCase			)} -- {timing:.4f} seconds"""			)

    for value in (262144, 1125899906842624, 1267650600228229401496703205376):
        for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
            benchmark_a_function(UpperCamelCase							,    UpperCamelCase			)
        print()


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 benchmark()


