


"""simple docstring"""




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


lowerCAmelCase	=							logging.get_logger(__name__)

lowerCAmelCase	=							{
    'salesforce/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json',
}


class 	_a							(      lowerCAmelCase_      ):
							_lowercase     :      Union[str, Any]  				=			'blip_2_vision_model'

							def __init__(							self:     Tuple   ,						UpperCamelCase_:     Dict=1_408   ,						UpperCamelCase_:     Tuple=6_144   ,						UpperCamelCase_:     Optional[Any]=39   ,						UpperCamelCase_:     Any=16   ,						UpperCamelCase_:     int=224   ,						UpperCamelCase_:     Any=14   ,						UpperCamelCase_:     Tuple="gelu"   ,						UpperCamelCase_:     Dict=0.00001   ,						UpperCamelCase_:     Optional[Any]=0.0   ,						UpperCamelCase_:     List[Any]=1E-1_0   ,						UpperCamelCase_:     Dict=True   ,						**UpperCamelCase_:     int   ,						)      ->       List[Any]:





									"""simple docstring"""







									super().__init__(**__lowerCAmelCase							)

									lowercase__						=				hidden_size
									lowercase__						=				intermediate_size
									lowercase__						=				num_hidden_layers
									lowercase__						=				num_attention_heads
									lowercase__						=				patch_size
									lowercase__						=				image_size
									lowercase__						=				initializer_range
									lowercase__						=				attention_dropout
									lowercase__						=				layer_norm_eps
									lowercase__						=				hidden_act
									lowercase__						=				qkv_bias


							@classmethod
							def 				lowerCamelCase_			(							cls:     Optional[int]   ,						UpperCamelCase_:     Union[str, os.PathLike]   ,						**UpperCamelCase_:     Optional[Any]							)      ->       List[str]:





									"""simple docstring"""







									cls._set_token_in_kwargs(__lowerCAmelCase							)

									lowercase__					,		lowercase__						=				cls.get_config_dict(__lowerCAmelCase   ,						**__lowerCAmelCase							)

									# get the vision config dict if we are loading from Blip2Config
									if config_dict.get('''model_type'''							) == "blip-2":
											lowercase__						=				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(__lowerCAmelCase   ,						**__lowerCAmelCase							)


class 	_a							(      lowerCAmelCase_      ):
							_lowercase     :      str  				=			'blip_2_qformer'

							def __init__(							self:     str   ,						UpperCamelCase_:     Dict=30_522   ,						UpperCamelCase_:     Tuple=768   ,						UpperCamelCase_:     List[str]=12   ,						UpperCamelCase_:     Union[str, Any]=12   ,						UpperCamelCase_:     Union[str, Any]=3_072   ,						UpperCamelCase_:     int="gelu"   ,						UpperCamelCase_:     Tuple=0.1   ,						UpperCamelCase_:     List[Any]=0.1   ,						UpperCamelCase_:     str=512   ,						UpperCamelCase_:     Optional[Any]=0.02   ,						UpperCamelCase_:     List[Any]=1E-1_2   ,						UpperCamelCase_:     List[Any]=0   ,						UpperCamelCase_:     Optional[Any]="absolute"   ,						UpperCamelCase_:     Union[str, Any]=2   ,						UpperCamelCase_:     Tuple=1_408   ,						**UpperCamelCase_:     Optional[int]   ,						)      ->       Any:





									"""simple docstring"""







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

									lowercase__						=				vocab_size
									lowercase__						=				hidden_size
									lowercase__						=				num_hidden_layers
									lowercase__						=				num_attention_heads
									lowercase__						=				hidden_act
									lowercase__						=				intermediate_size
									lowercase__						=				hidden_dropout_prob
									lowercase__						=				attention_probs_dropout_prob
									lowercase__						=				max_position_embeddings
									lowercase__						=				initializer_range
									lowercase__						=				layer_norm_eps
									lowercase__						=				position_embedding_type
									lowercase__						=				cross_attention_frequency
									lowercase__						=				encoder_hidden_size


							@classmethod
							def 				lowerCamelCase_			(							cls:     Union[str, Any]   ,						UpperCamelCase_:     Union[str, os.PathLike]   ,						**UpperCamelCase_:     Tuple							)      ->       List[str]:





									"""simple docstring"""







									cls._set_token_in_kwargs(__lowerCAmelCase							)

									lowercase__					,		lowercase__						=				cls.get_config_dict(__lowerCAmelCase   ,						**__lowerCAmelCase							)

									# get the qformer config dict if we are loading from Blip2Config
									if config_dict.get('''model_type'''							) == "blip-2":
											lowercase__						=				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(__lowerCAmelCase   ,						**__lowerCAmelCase							)


class 	_a							(      lowerCAmelCase_      ):
							_lowercase     :      List[str]  				=			'blip-2'
							_lowercase     :      int  				=			True

							def __init__(							self:     Any   ,						UpperCamelCase_:     Union[str, Any]=None   ,						UpperCamelCase_:     Union[str, Any]=None   ,						UpperCamelCase_:     Dict=None   ,						UpperCamelCase_:     Any=32   ,						**UpperCamelCase_:     List[Any]							)      ->       List[Any]:





									"""simple docstring"""







									super().__init__(**__lowerCAmelCase							)

									if vision_config is None:
											lowercase__						=				{}
											logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.'''							)

									if qformer_config is None:
											lowercase__						=				{}
											logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.'''							)

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

									lowercase__						=				BlipaVisionConfig(**__lowerCAmelCase							)
									lowercase__						=				BlipaQFormerConfig(**__lowerCAmelCase							)
									lowercase__						=				text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
									lowercase__						=				CONFIG_MAPPING[text_model_type](**__lowerCAmelCase							)

									lowercase__						=				self.text_config.tie_word_embeddings
									lowercase__						=				self.text_config.is_encoder_decoder

									lowercase__						=				num_query_tokens
									lowercase__						=				self.vision_config.hidden_size
									lowercase__						=				self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
									lowercase__						=				1.0
									lowercase__						=				0.02

							@classmethod
							def 				lowerCamelCase_			(							cls:     Optional[int]   ,						UpperCamelCase_:     BlipaVisionConfig   ,						UpperCamelCase_:     BlipaQFormerConfig   ,						UpperCamelCase_:     PretrainedConfig   ,						**UpperCamelCase_:     Dict   ,						)      ->       Optional[Any]:





									"""simple docstring"""







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


							def 				lowerCamelCase_			(							self:     Optional[Any]							)      ->       List[Any]:





									"""simple docstring"""







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






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

import datasets


lowerCAmelCase	=							'\\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'


lowerCAmelCase	=							'\\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'


lowerCAmelCase	=							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      ):

							def 				lowerCamelCase_			(							self:     List[str]							)      ->       Tuple:





									"""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 				lowerCamelCase_			(							self:     Union[str, Any]   ,						UpperCamelCase_:     Any   ,						UpperCamelCase_:     int							)      ->       List[str]:





									"""simple docstring"""







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


