






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


SCREAMING_SNAKE_CASE 							=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE 							=						{
    'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json',
}
class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Tuple =					"instructblip_vision_model"


 def __init__(	self							,  _A=1408							,  _A=6144							,  _A=39							,  _A=16							,  _A=224							,  _A=14							,  _A="gelu"							,  _A=1e-6							,  _A=0.0							,  _A=1e-10							,  _A=True							,  **_A							,  ) ->		List[str]:

     """simple docstring"""



     super().__init__(**_A)

     _UpperCAmelCase				:      Tuple			  =				hidden_size
     _UpperCAmelCase				:      Any			  =				intermediate_size
     _UpperCAmelCase				:      Any			  =				num_hidden_layers
     _UpperCAmelCase				:      int			  =				num_attention_heads
     _UpperCAmelCase				:      List[Any]			  =				patch_size
     _UpperCAmelCase				:      str			  =				image_size
     _UpperCAmelCase				:      List[Any]			  =				initializer_range
     _UpperCAmelCase				:      Optional[int]			  =				attention_dropout
     _UpperCAmelCase				:      Optional[int]			  =				layer_norm_eps
     _UpperCAmelCase				:      Optional[int]			  =				hidden_act
     _UpperCAmelCase				:      Optional[int]			  =				qkv_bias


 @classmethod
 def  snake_case__				(	cls							,  _A							,  **_A) ->		"PretrainedConfig":

     """simple docstring"""



     cls._set_token_in_kwargs(_A)

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

     # get the vision config dict if we are loading from InstructBlipConfig
     if config_dict.get('''model_type''') == "instructblip":
         _UpperCAmelCase				:      Any			  =				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(_A							,  **_A)



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			List[Any] =					"instructblip_qformer"


 def __init__(	self							,  _A=30522							,  _A=768							,  _A=12							,  _A=12							,  _A=3072							,  _A="gelu"							,  _A=0.1							,  _A=0.1							,  _A=512							,  _A=0.02							,  _A=1e-12							,  _A=0							,  _A="absolute"							,  _A=2							,  _A=1408							,  **_A							,  ) ->		List[Any]:

     """simple docstring"""



     super().__init__(pad_token_id=_A							,  **_A)

     _UpperCAmelCase				:      Optional[int]			  =				vocab_size
     _UpperCAmelCase				:      str			  =				hidden_size
     _UpperCAmelCase				:      Tuple			  =				num_hidden_layers
     _UpperCAmelCase				:      Optional[int]			  =				num_attention_heads
     _UpperCAmelCase				:      str			  =				hidden_act
     _UpperCAmelCase				:      Dict			  =				intermediate_size
     _UpperCAmelCase				:      Union[str, Any]			  =				hidden_dropout_prob
     _UpperCAmelCase				:      List[Any]			  =				attention_probs_dropout_prob
     _UpperCAmelCase				:      Union[str, Any]			  =				max_position_embeddings
     _UpperCAmelCase				:      List[Any]			  =				initializer_range
     _UpperCAmelCase				:      Tuple			  =				layer_norm_eps
     _UpperCAmelCase				:      Optional[Any]			  =				position_embedding_type
     _UpperCAmelCase				:      Dict			  =				cross_attention_frequency
     _UpperCAmelCase				:      str			  =				encoder_hidden_size


 @classmethod
 def  snake_case__				(	cls							,  _A							,  **_A) ->		"PretrainedConfig":

     """simple docstring"""



     cls._set_token_in_kwargs(_A)

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

     # get the qformer config dict if we are loading from InstructBlipConfig
     if config_dict.get('''model_type''') == "instructblip":
         _UpperCAmelCase				:      Union[str, Any]			  =				config_dict['''qformer_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(_A							,  **_A)



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			List[Any] =					"instructblip"
 _SCREAMING_SNAKE_CASE							:			Tuple =					True


 def __init__(	self							,  _A=None							,  _A=None							,  _A=None							,  _A=32							,  **_A) ->		str:

     """simple docstring"""



     super().__init__(**_A)

     if vision_config is None:
         _UpperCAmelCase				:      Dict			  =				{}
         logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.''')

     if qformer_config is None:
         _UpperCAmelCase				:      Optional[int]			  =				{}
         logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.''')

     if text_config is None:
         _UpperCAmelCase				:      Any			  =				{}
         logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''')

     _UpperCAmelCase				:      Any			  =				InstructBlipVisionConfig(**_A)
     _UpperCAmelCase				:      List[Any]			  =				InstructBlipQFormerConfig(**_A)
     _UpperCAmelCase				:      Optional[int]			  =				text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
     _UpperCAmelCase				:      str			  =				CONFIG_MAPPING[text_model_type](**_A)

     _UpperCAmelCase				:      Dict			  =				self.text_config.tie_word_embeddings
     _UpperCAmelCase				:      Union[str, Any]			  =				self.text_config.is_encoder_decoder

     _UpperCAmelCase				:      Any			  =				num_query_tokens
     _UpperCAmelCase				:      Any			  =				self.vision_config.hidden_size
     _UpperCAmelCase				:      Optional[Any]			  =				self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
     _UpperCAmelCase				:      Optional[Any]			  =				1.0
     _UpperCAmelCase				:      Optional[int]			  =				0.02


 @classmethod
 def  snake_case__				(	cls							,  _A							,  _A							,  _A							,  **_A							,  ) ->		List[str]:

     """simple docstring"""



     return cls(
         vision_config=vision_config.to_dict()							,  qformer_config=qformer_config.to_dict()							,  text_config=text_config.to_dict()							,  **_A							,  )


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

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				copy.deepcopy(self.__dict__)
     _UpperCAmelCase				:      List[str]			  =				self.vision_config.to_dict()
     _UpperCAmelCase				:      Optional[int]			  =				self.qformer_config.to_dict()
     _UpperCAmelCase				:      List[str]			  =				self.text_config.to_dict()
     _UpperCAmelCase				:      int			  =				self.__class__.model_type
     return output












import math_equivalence  # From: git+https://github.com/hendrycks/math.git

import datasets


SCREAMING_SNAKE_CASE 							=						'\\n@article{hendrycksmath2021,\n  title={Measuring Mathematical Problem Solving With the MATH Dataset},\n  author={Dan Hendrycks\n    and Collin Burns\n    and Saurav Kadavath\n    and Akul Arora\n    and Steven Basart\n    and Eric Tang\n    and Dawn Song\n    and Jacob Steinhardt},\n  journal={arXiv preprint arXiv:2103.03874},\n  year={2021}\n}\n'


SCREAMING_SNAKE_CASE 							=						'\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n'


SCREAMING_SNAKE_CASE 							=						R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n    predictions: list of predictions to score. Each prediction\n        is a string that contains natural language and LaTex.\n    references: list of reference for each prediction. Each\n        reference is a string that contains natural language\n        and LaTex.\nReturns:\n    accuracy: accuracy after canonicalizing inputs\n        (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n    >>> metric = datasets.load_metric("competition_math")\n    >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n    >>> print(results)\n    {\'accuracy\': 1.0}\n'
@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION ,   _KWARGS_DESCRIPTION			)
class 							A_    (						datasets.Metric			):






 '''simple docstring'''




 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     return datasets.MetricInfo(
         description=_DESCRIPTION							,  citation=_CITATION							,  inputs_description=_KWARGS_DESCRIPTION							,  features=datasets.Features(
             {
                 '''predictions''': datasets.Value('''string'''),
                 '''references''': datasets.Value('''string'''),
             })							,  homepage='''https://github.com/hendrycks/math'''							,  codebase_urls=['''https://github.com/hendrycks/math''']							,  )


 def  snake_case__				(	self							,  _A							,  _A) ->		Tuple:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				0.0
     for i, j in zip(_A							,  _A):
         n_correct += 1.0 if math_equivalence.is_equiv(_A							,  _A) else 0.0
     _UpperCAmelCase				:      Tuple			  =				n_correct / len(_A)
     return {
         "accuracy": accuracy,
     }




