




import copy
import os
from typing import Union

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


_lowerCamelCase      :  List[str]      						=						logging.get_logger(__name__)

_lowerCamelCase      :  str      						=						{
    "google/pix2struct-textcaps-base": (
        "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"
    ),
}
class        __snake_case  (_a		):
				lowerCAmelCase__				=     "pix2struct_text_model"
				lowerCAmelCase__				=     ["past_key_values"]
				lowerCAmelCase__				=     {
				    "hidden_size": "hidden_size",
				    "num_attention_heads": "num_heads",
				    "num_hidden_layers": "num_layers",
				}



				def __init__(      self      :		Optional[Any]		,	_UpperCAmelCase      :		List[Any]=5_0244		,	_UpperCAmelCase      :		Optional[int]=768		,	_UpperCAmelCase      :		int=64		,	_UpperCAmelCase      :		Optional[int]=2048		,	_UpperCAmelCase      :		Dict=12		,	_UpperCAmelCase      :		Optional[int]=12		,	_UpperCAmelCase      :		Tuple=32		,	_UpperCAmelCase      :		Optional[int]=128		,	_UpperCAmelCase      :		List[Any]=0.1		,	_UpperCAmelCase      :		Optional[int]=1E-6		,	_UpperCAmelCase      :		Dict=1.0		,	_UpperCAmelCase      :		List[Any]="gelu_new"		,	_UpperCAmelCase      :		List[Any]=0		,	_UpperCAmelCase      :		Any=False		,	_UpperCAmelCase      :		Dict=0		,	_UpperCAmelCase      :		List[Any]=1		,	_UpperCAmelCase      :		str=False		,	_UpperCAmelCase      :		List[Any]=True		,	**_UpperCAmelCase      :		List[str]		,	)  ->    List[str]:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      vocab_size
								_lowerCAmelCase    :    int										=      hidden_size
								_lowerCAmelCase    :    List[str]										=      d_kv
								_lowerCAmelCase    :    Any										=      d_ff
								_lowerCAmelCase    :    Optional[Any]										=      num_layers
								_lowerCAmelCase    :    List[str]										=      num_heads
								_lowerCAmelCase    :    List[Any]										=      relative_attention_num_buckets
								_lowerCAmelCase    :    List[str]										=      relative_attention_max_distance
								_lowerCAmelCase    :    str										=      dropout_rate
								_lowerCAmelCase    :    List[Any]										=      layer_norm_epsilon
								_lowerCAmelCase    :    str										=      initializer_factor
								_lowerCAmelCase    :    int										=      use_cache

								_lowerCAmelCase    :    str										=      eos_token_id
								_lowerCAmelCase    :    List[str]										=      decoder_start_token_id

								# for backwards compatibility
								_lowerCAmelCase    :    Union[str, Any]										=      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      :		str		,	_UpperCAmelCase      :		Union[str, os.PathLike]		,	**_UpperCAmelCase      :		Union[str, Any]      )  ->    "PretrainedConfig":





								'''simple docstring'''




								cls._set_token_in_kwargs(_UpperCAmelCase      )

								_lowerCAmelCase					,    _lowerCAmelCase    :    int										=      cls.get_config_dict(_UpperCAmelCase		,	**_UpperCAmelCase      )

								# get the text config dict if we are loading from Pix2StructConfig
								if config_dict.get("""model_type"""      ) == "pix2struct":
												_lowerCAmelCase    :    Tuple										=      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        __snake_case  (_a		):
				lowerCAmelCase__				=     "pix2struct_vision_model"



				def __init__(      self      :		int		,	_UpperCAmelCase      :		Any=768		,	_UpperCAmelCase      :		List[Any]=768		,	_UpperCAmelCase      :		Optional[int]=2048		,	_UpperCAmelCase      :		List[Any]=64		,	_UpperCAmelCase      :		Optional[int]=12		,	_UpperCAmelCase      :		Optional[Any]=12		,	_UpperCAmelCase      :		int="gelu_new"		,	_UpperCAmelCase      :		Dict=1E-6		,	_UpperCAmelCase      :		Optional[Any]=0.0		,	_UpperCAmelCase      :		Tuple=0.0		,	_UpperCAmelCase      :		Optional[int]=1E-10		,	_UpperCAmelCase      :		Union[str, Any]=1.0		,	_UpperCAmelCase      :		Union[str, Any]=4096		,	_UpperCAmelCase      :		int=32		,	_UpperCAmelCase      :		Any=128		,	**_UpperCAmelCase      :		int		,	)  ->    List[str]:





								'''simple docstring'''




								super().__init__(**_UpperCAmelCase      )

								_lowerCAmelCase    :    List[Any]										=      hidden_size
								_lowerCAmelCase    :    str										=      patch_embed_hidden_size
								_lowerCAmelCase    :    str										=      d_ff
								_lowerCAmelCase    :    int										=      dropout_rate
								_lowerCAmelCase    :    Dict										=      num_hidden_layers
								_lowerCAmelCase    :    Optional[Any]										=      num_attention_heads
								_lowerCAmelCase    :    Union[str, Any]										=      initializer_range
								_lowerCAmelCase    :    Tuple										=      initializer_factor
								_lowerCAmelCase    :    Optional[Any]										=      attention_dropout
								_lowerCAmelCase    :    List[str]										=      layer_norm_eps
								_lowerCAmelCase    :    Any										=      dense_act_fn
								_lowerCAmelCase    :    str										=      seq_len
								_lowerCAmelCase    :    List[str]										=      relative_attention_num_buckets
								_lowerCAmelCase    :    List[Any]										=      relative_attention_max_distance
								_lowerCAmelCase    :    List[Any]										=      d_kv



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





								'''simple docstring'''




								cls._set_token_in_kwargs(_UpperCAmelCase      )

								_lowerCAmelCase					,    _lowerCAmelCase    :    List[Any]										=      cls.get_config_dict(_UpperCAmelCase		,	**_UpperCAmelCase      )

								# get the vision config dict if we are loading from Pix2StructConfig
								if config_dict.get("""model_type"""      ) == "pix2struct":
												_lowerCAmelCase    :    Tuple										=      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        __snake_case  (_a		):
				lowerCAmelCase__				=     "pix2struct"
				lowerCAmelCase__				=     True



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





								'''simple docstring'''




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

								if text_config is None:
												_lowerCAmelCase    :    Tuple										=      {}
												logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values."""      )

								if vision_config is None:
												_lowerCAmelCase    :    int										=      {}
												logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values."""      )

								_lowerCAmelCase    :    Union[str, Any]										=      PixaStructTextConfig(**_UpperCAmelCase      )
								_lowerCAmelCase    :    int										=      PixaStructVisionConfig(**_UpperCAmelCase      )

								_lowerCAmelCase    :    int										=      self.text_config.decoder_start_token_id
								_lowerCAmelCase    :    str										=      self.text_config.pad_token_id
								_lowerCAmelCase    :    Tuple										=      self.text_config.eos_token_id

								_lowerCAmelCase    :    Optional[Any]										=      initializer_factor
								_lowerCAmelCase    :    str										=      initializer_range

								_lowerCAmelCase    :    int										=      self.initializer_range
								_lowerCAmelCase    :    int										=      self.initializer_range

								_lowerCAmelCase    :    Union[str, Any]										=      is_vqa



				@classmethod
				def       SCREAMING_SNAKE_CASE       (      cls      :		Optional[Any]		,	_UpperCAmelCase      :		PixaStructTextConfig		,	_UpperCAmelCase      :		PixaStructVisionConfig		,	**_UpperCAmelCase      :		Optional[int]      )  ->    Optional[int]:





								'''simple docstring'''




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



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





								'''simple docstring'''




								_lowerCAmelCase    :    List[str]										=      copy.deepcopy(self.__dict__      )
								_lowerCAmelCase    :    List[str]										=      self.text_config.to_dict()
								_lowerCAmelCase    :    int										=      self.vision_config.to_dict()
								_lowerCAmelCase    :    Dict										=      self.__class__.model_type
								return output







from __future__ import annotations

from decimal import Decimal

from numpy import array




def 							_UpperCAmelCase  (UpperCamelCase_ : list[list[float]]       ):
				'''simple docstring'''
				_lowerCAmelCase    :    int										=      Decimal

				# Check if the provided matrix has 2 rows and 2 columns
				# since this implementation only works for 2x2 matrices
				if len(UpperCamelCase_       ) == 2 and len(matrix[0]       ) == 2 and len(matrix[1]       ) == 2:
								# Calculate the determinant of the matrix
								_lowerCAmelCase    :    Optional[Any]										=      float(
								    d(matrix[0][0]       ) * d(matrix[1][1]       ) - d(matrix[1][0]       ) * d(matrix[0][1]       )       )
								if determinant == 0:
												raise ValueError("""This matrix has no inverse."""       )

								# Creates a copy of the matrix with swapped positions of the elements
								_lowerCAmelCase    :    Union[str, Any]										=      [[0.0, 0.0], [0.0, 0.0]]
								_lowerCAmelCase					,    _lowerCAmelCase    :    Any										=      matrix[1][1], matrix[0][0]
								_lowerCAmelCase					,    _lowerCAmelCase    :    Optional[Any]										=      -matrix[1][0], -matrix[0][1]

								# Calculate the inverse of the matrix
								return [
								    [(float(d(UpperCamelCase_       )       ) / determinant) or 0.0 for n in row] for row in swapped_matrix
								]
				elif (
				    len(UpperCamelCase_       ) == 3
				    and len(matrix[0]       ) == 3
				    and len(matrix[1]       ) == 3
				    and len(matrix[2]       ) == 3
				):
								# Calculate the determinant of the matrix using Sarrus rule
								_lowerCAmelCase    :    List[str]										=      float(
								    (
								        (d(matrix[0][0]       ) * d(matrix[1][1]       ) * d(matrix[2][2]       ))
								        + (d(matrix[0][1]       ) * d(matrix[1][2]       ) * d(matrix[2][0]       ))
								        + (d(matrix[0][2]       ) * d(matrix[1][0]       ) * d(matrix[2][1]       ))
								    )
								    - (
								        (d(matrix[0][2]       ) * d(matrix[1][1]       ) * d(matrix[2][0]       ))
								        + (d(matrix[0][1]       ) * d(matrix[1][0]       ) * d(matrix[2][2]       ))
								        + (d(matrix[0][0]       ) * d(matrix[1][2]       ) * d(matrix[2][1]       ))
								    )       )
								if determinant == 0:
												raise ValueError("""This matrix has no inverse."""       )

								# Creating cofactor matrix
								_lowerCAmelCase    :    Optional[Any]										=      [
								    [d(0.0       ), d(0.0       ), d(0.0       )],
								    [d(0.0       ), d(0.0       ), d(0.0       )],
								    [d(0.0       ), d(0.0       ), d(0.0       )],
								]
								_lowerCAmelCase    :    Optional[Any]										=      (d(matrix[1][1]       ) * d(matrix[2][2]       )) - (
								    d(matrix[1][2]       ) * d(matrix[2][1]       )
								)
								_lowerCAmelCase    :    str										=      -(
								    (d(matrix[1][0]       ) * d(matrix[2][2]       )) - (d(matrix[1][2]       ) * d(matrix[2][0]       ))
								)
								_lowerCAmelCase    :    Any										=      (d(matrix[1][0]       ) * d(matrix[2][1]       )) - (
								    d(matrix[1][1]       ) * d(matrix[2][0]       )
								)
								_lowerCAmelCase    :    List[str]										=      -(
								    (d(matrix[0][1]       ) * d(matrix[2][2]       )) - (d(matrix[0][2]       ) * d(matrix[2][1]       ))
								)
								_lowerCAmelCase    :    Tuple										=      (d(matrix[0][0]       ) * d(matrix[2][2]       )) - (
								    d(matrix[0][2]       ) * d(matrix[2][0]       )
								)
								_lowerCAmelCase    :    Any										=      -(
								    (d(matrix[0][0]       ) * d(matrix[2][1]       )) - (d(matrix[0][1]       ) * d(matrix[2][0]       ))
								)
								_lowerCAmelCase    :    int										=      (d(matrix[0][1]       ) * d(matrix[1][2]       )) - (
								    d(matrix[0][2]       ) * d(matrix[1][1]       )
								)
								_lowerCAmelCase    :    Optional[Any]										=      -(
								    (d(matrix[0][0]       ) * d(matrix[1][2]       )) - (d(matrix[0][2]       ) * d(matrix[1][0]       ))
								)
								_lowerCAmelCase    :    Tuple										=      (d(matrix[0][0]       ) * d(matrix[1][1]       )) - (
								    d(matrix[0][1]       ) * d(matrix[1][0]       )
								)

								# Transpose the cofactor matrix (Adjoint matrix)
								_lowerCAmelCase    :    List[str]										=      array(UpperCamelCase_       )
								for i in range(3       ):
												for j in range(3       ):
																_lowerCAmelCase    :    List[Any]										=      cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
								_lowerCAmelCase    :    Tuple										=      array(UpperCamelCase_       )
								for i in range(3       ):
												for j in range(3       ):
																inverse_matrix[i][j] /= d(UpperCamelCase_       )

        # Calculate the inverse of the matrix
								return [[float(d(UpperCamelCase_       )       ) or 0.0 for n in row] for row in inverse_matrix]
				raise ValueError("""Please provide a matrix of size 2x2 or 3x3."""       )

