



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


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

a__   :					List[Any] 						=      {
    "Salesforce/instruct-blip-flan-t5": "https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json",
}



class    UpperCAmelCase__(				lowerCamelCase						):

   '''simple docstring'''




   A     :	str												=     "instructblip_vision_model"


   def __init__(    self	:      Tuple      ,					lowerCAmelCase	:      List[str]=14_08      ,					lowerCAmelCase	:      Union[str, Any]=61_44      ,					lowerCAmelCase	:      Optional[Any]=39      ,					lowerCAmelCase	:      Union[str, Any]=16      ,					lowerCAmelCase	:      Union[str, Any]=2_24      ,					lowerCAmelCase	:      Optional[int]=14      ,					lowerCAmelCase	:      List[Any]="gelu"      ,					lowerCAmelCase	:      Optional[Any]=1E-6      ,					lowerCAmelCase	:      Optional[Any]=0.0      ,					lowerCAmelCase	:      List[Any]=1E-1_0      ,					lowerCAmelCase	:      Any=True      ,					**lowerCAmelCase	:      Dict      ,					)						->					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       UpperCAmelCase		(    cls	:      Optional[int]      ,					lowerCAmelCase	:      Union[str, os.PathLike]      ,					**lowerCAmelCase	:      Optional[int])						->					"PretrainedConfig":




         """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 InstructBlipConfig
         if config_dict.get('model_type') == "instructblip":
               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    UpperCAmelCase__(				lowerCamelCase						):

   '''simple docstring'''




   A     :	Dict												=     "instructblip_qformer"


   def __init__(    self	:      Union[str, Any]      ,					lowerCAmelCase	:      str=3_05_22      ,					lowerCAmelCase	:      Tuple=7_68      ,					lowerCAmelCase	:      Optional[int]=12      ,					lowerCAmelCase	:      int=12      ,					lowerCAmelCase	:      str=30_72      ,					lowerCAmelCase	:      Optional[Any]="gelu"      ,					lowerCAmelCase	:      Any=0.1      ,					lowerCAmelCase	:      Any=0.1      ,					lowerCAmelCase	:      List[str]=5_12      ,					lowerCAmelCase	:      List[Any]=0.02      ,					lowerCAmelCase	:      Any=1E-1_2      ,					lowerCAmelCase	:      Any=0      ,					lowerCAmelCase	:      Union[str, Any]="absolute"      ,					lowerCAmelCase	:      Any=2      ,					lowerCAmelCase	:      str=14_08      ,					**lowerCAmelCase	:      List[Any]      ,					)						->					str:




         """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       UpperCAmelCase		(    cls	:      List[str]      ,					lowerCAmelCase	:      Union[str, os.PathLike]      ,					**lowerCAmelCase	:      Any)						->					"PretrainedConfig":




         """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 InstructBlipConfig
         if config_dict.get('model_type') == "instructblip":
               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    UpperCAmelCase__(				lowerCamelCase						):

   '''simple docstring'''




   A     :	Tuple												=     "instructblip"
   A     :	Optional[int]												=     True


   def __init__(    self	:      Optional[int]      ,					lowerCAmelCase	:      Any=None      ,					lowerCAmelCase	:      Optional[Any]=None      ,					lowerCAmelCase	:      Dict=None      ,					lowerCAmelCase	:      Union[str, Any]=32      ,					**lowerCAmelCase	:      int)						->					Optional[Any]:




         """simple docstring"""

         super().__init__(**lowerCAmelCase)

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

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

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

         lowercase__  =	InstructBlipVisionConfig(**lowerCAmelCase)
         lowercase__  =	InstructBlipQFormerConfig(**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       UpperCAmelCase		(    cls	:      Dict      ,					lowerCAmelCase	:      InstructBlipVisionConfig      ,					lowerCAmelCase	:      InstructBlipQFormerConfig      ,					lowerCAmelCase	:      PretrainedConfig      ,					**lowerCAmelCase	:      Tuple      ,					)						->					List[str]:




         """simple docstring"""

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



   def       UpperCAmelCase		(    self	:      Optional[Any])						->					Union[str, 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





from sklearn.metrics import matthews_corrcoef

import datasets


a__   :					Any 						=      "\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

a__   :					Any 						=      "\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

a__   :					str 						=      "\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,				_KWARGS_DESCRIPTION						)
class    UpperCAmelCase__(				datasets.Metric						):

   '''simple docstring'''




   def       UpperCAmelCase		(    self	:      List[Any])						->					int:




         """simple docstring"""

         return datasets.MetricInfo(
             description=_DESCRIPTION      ,					citation=_CITATION      ,					inputs_description=_KWARGS_DESCRIPTION      ,					features=datasets.Features(
                 {
                     'predictions': datasets.Value('int32'),
                     'references': datasets.Value('int32'),
                 })      ,					reference_urls=[
                 'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'
             ]      ,					)



   def       UpperCAmelCase		(    self	:      Dict      ,					lowerCAmelCase	:      Dict      ,					lowerCAmelCase	:      Optional[int]      ,					lowerCAmelCase	:      Union[str, Any]=None)						->					Any:




         """simple docstring"""

         return {
             "matthews_correlation": float(matthews_corrcoef(lowerCAmelCase      ,					lowerCAmelCase      ,					sample_weight=lowerCAmelCase)),
         }
