




import copy
import os
from typing import Union

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


_lowerCamelCase      :						Union[str, Any]							=  logging.get_logger(__name__)

_lowerCamelCase      :						List[str]							=  {
    """google/pix2struct-textcaps-base""": (
        """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"""
    ),
}


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''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 :      Dict   ,					UpperCAmelCase__ :      Any=50_244   ,					UpperCAmelCase__ :      Tuple=768   ,					UpperCAmelCase__ :      Union[str, Any]=64   ,					UpperCAmelCase__ :      Union[str, Any]=2_048   ,					UpperCAmelCase__ :      List[str]=12   ,					UpperCAmelCase__ :      Any=12   ,					UpperCAmelCase__ :      int=32   ,					UpperCAmelCase__ :      Optional[int]=128   ,					UpperCAmelCase__ :      str=0.1   ,					UpperCAmelCase__ :      List[str]=1e-6   ,					UpperCAmelCase__ :      Dict=1.0   ,					UpperCAmelCase__ :      Any="gelu_new"   ,					UpperCAmelCase__ :      Dict=0   ,					UpperCAmelCase__ :      Union[str, Any]=False   ,					UpperCAmelCase__ :      int=0   ,					UpperCAmelCase__ :      List[str]=1   ,					UpperCAmelCase__ :      str=False   ,					UpperCAmelCase__ :      Any=True   ,					**UpperCAmelCase__ :      Union[str, Any]   ,					)		->Union[str, Any]:





           '''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=UpperCAmelCase__   ,					eos_token_id=UpperCAmelCase__   ,					decoder_start_token_id=UpperCAmelCase__   ,					tie_word_embeddings=UpperCAmelCase__   ,					is_decoder=UpperCAmelCase__   ,					**UpperCAmelCase__   ,					)





    @classmethod
    def 			SCREAMING_SNAKE_CASE				(     cls :      Optional[Any]   ,					UpperCAmelCase__ :      Union[str, os.PathLike]   ,					**UpperCAmelCase__ :      Any)		->"PretrainedConfig":





           '''simple docstring'''

           cls._set_token_in_kwargs(UpperCAmelCase__)

           A__					,				A__ 					=       cls.get_config_dict(UpperCAmelCase__   ,					**UpperCAmelCase__)

           # 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(UpperCAmelCase__   ,					**UpperCAmelCase__)


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''pix2struct_vision_model'''


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





           '''simple docstring'''

           super().__init__(**UpperCAmelCase__)

           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 			SCREAMING_SNAKE_CASE				(     cls :      Tuple   ,					UpperCAmelCase__ :      Union[str, os.PathLike]   ,					**UpperCAmelCase__ :      Tuple)		->"PretrainedConfig":





           '''simple docstring'''

           cls._set_token_in_kwargs(UpperCAmelCase__)

           A__					,				A__ 					=       cls.get_config_dict(UpperCAmelCase__   ,					**UpperCAmelCase__)

           # 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(UpperCAmelCase__   ,					**UpperCAmelCase__)


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''pix2struct'''
    UpperCAmelCase__				    = True


    def __init__(     self :      List[str]   ,					UpperCAmelCase__ :      Union[str, Any]=None   ,					UpperCAmelCase__ :      Tuple=None   ,					UpperCAmelCase__ :      str=1.0   ,					UpperCAmelCase__ :      Optional[int]=0.02   ,					UpperCAmelCase__ :      List[Any]=False   ,					UpperCAmelCase__ :      List[Any]=False   ,					UpperCAmelCase__ :      Dict=True   ,					**UpperCAmelCase__ :      List[Any]   ,					)		->Union[str, Any]:





           '''simple docstring'''

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

           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(**UpperCAmelCase__)
           A__ 					=       PixaStructVisionConfig(**UpperCAmelCase__)

           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 			SCREAMING_SNAKE_CASE				(     cls :      Optional[Any]   ,					UpperCAmelCase__ :      PixaStructTextConfig   ,					UpperCAmelCase__ :      PixaStructVisionConfig   ,					**UpperCAmelCase__ :      Dict)		->Tuple:





           '''simple docstring'''

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





    def 			SCREAMING_SNAKE_CASE				(     self :      List[Any])		->List[str]:





           '''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





from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
		import timm


if is_torch_available():
		from torch import Tensor







class 					__lowercase  (						_SCREAMING_SNAKE_CASE		,       _SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		int								=	'''pixel_values'''
							UpperCAmelCase_						:		List[str]								=	False
							UpperCAmelCase_						:		Tuple								=	TimmBackboneConfig




							def __init__(					self    ,						__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       int:
														requires_backends(self    ,						'''timm'''						)
														super().__init__(__UpperCAmelCase						)
														A      :					List[str]      		=					config

														if config.backbone is None:
																					raise ValueError('''backbone is not set in the config. Please set it to a timm model name.'''						)

														if config.backbone not in timm.list_models():
																					raise ValueError(f'backbone {config.backbone} is not supported by timm.'						)

														if hasattr(__UpperCAmelCase    ,						'''out_features'''						) and config.out_features is not None:
																					raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.'''						)

														A      :					str      		=					getattr(__UpperCAmelCase    ,						'''use_pretrained_backbone'''    ,						__UpperCAmelCase						)
														if pretrained is None:
																					raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.'''						)

														# We just take the final layer by default. This matches the default for the transformers models.
														A      :					Optional[int]      		=					config.out_indices if getattr(__UpperCAmelCase    ,						'''out_indices'''    ,						__UpperCAmelCase						) is not None else (-1,)

														A      :					str      		=					timm.create_model(
														    config.backbone    ,						pretrained=__UpperCAmelCase    ,						features_only=config.features_only    ,						in_chans=config.num_channels    ,						out_indices=__UpperCAmelCase    ,						**__UpperCAmelCase    ,						)
														# These are used to control the output of the model when called. If output_hidden_states is True, then
														# return_layers is modified to include all layers.
														A      :					str      		=					self._backbone.return_layers
														A      :					Any      		=					{layer['''module''']: str(__UpperCAmelCase						) for i, layer in enumerate(self._backbone.feature_info.info						)}
														super()._init_backbone(__UpperCAmelCase						)




							@classmethod
							def       snake_case			(					cls    ,						__UpperCAmelCase    ,						*__UpperCAmelCase    ,						**__UpperCAmelCase						)		->       Any:
														requires_backends(cls    ,						['''vision''', '''timm''']						)
														from ...models.timm_backbone import TimmBackboneConfig

														A      :					Optional[Any]      		=					kwargs.pop('''config'''    ,						TimmBackboneConfig()						)

														A      :					str      		=					kwargs.pop('''use_timm_backbone'''    ,						__UpperCAmelCase						)
														if not use_timm:
																					raise ValueError('''use_timm_backbone must be True for timm backbones'''						)

														A      :					Optional[int]      		=					kwargs.pop('''num_channels'''    ,						config.num_channels						)
														A      :					List[str]      		=					kwargs.pop('''features_only'''    ,						config.features_only						)
														A      :					Optional[int]      		=					kwargs.pop('''use_pretrained_backbone'''    ,						config.use_pretrained_backbone						)
														A      :					Optional[int]      		=					kwargs.pop('''out_indices'''    ,						config.out_indices						)
														A      :					int      		=					TimmBackboneConfig(
														    backbone=__UpperCAmelCase    ,						num_channels=__UpperCAmelCase    ,						features_only=__UpperCAmelCase    ,						use_pretrained_backbone=__UpperCAmelCase    ,						out_indices=__UpperCAmelCase    ,						)
														return super()._from_config(__UpperCAmelCase    ,						**__UpperCAmelCase						)




							def       snake_case			(					self    ,						__UpperCAmelCase						)		->       Any:
														pass






							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						__UpperCAmelCase=None    ,						**__UpperCAmelCase						)		->       Union[BackboneOutput, Tuple[Tensor, ...]]:
														A      :					Optional[int]      		=					return_dict if return_dict is not None else self.config.use_return_dict
														A      :					str      		=					(
														    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
														)
														A      :					Any      		=					output_attentions if output_attentions is not None else self.config.output_attentions

														if output_attentions:
																					raise ValueError('''Cannot output attentions for timm backbones at the moment'''						)

														if output_hidden_states:
																					# We modify the return layers to include all the stages of the backbone
																					A      :					Dict      		=					self._all_layers
																					A      :					int      		=					self._backbone(__UpperCAmelCase    ,						**__UpperCAmelCase						)
																					A      :					Any      		=					self._return_layers
																					A      :					Union[str, Any]      		=					tuple(hidden_states[i] for i in self.out_indices						)
														else:
																					A      :					Optional[int]      		=					self._backbone(__UpperCAmelCase    ,						**__UpperCAmelCase						)
																					A      :					List[Any]      		=					None

														A      :					str      		=					tuple(__UpperCAmelCase						)
														A      :					int      		=					tuple(__UpperCAmelCase						) if hidden_states is not None else None

														if not return_dict:
																					A      :					Optional[Any]      		=					(feature_maps,)
																					if output_hidden_states:
																												A      :					Tuple      		=					output + (hidden_states,)
																					return output

														return BackboneOutput(feature_maps=__UpperCAmelCase    ,						hidden_states=__UpperCAmelCase    ,						attentions=__UpperCAmelCase						)






