"""simple docstring"""






import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers.models.esm.modeling_esmfold import EsmForProteinFolding


class     UpperCAmelCase						:



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=13    ,			_UpperCAmelCase=7    ,			_UpperCAmelCase=False    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=False    ,			_UpperCAmelCase=False    ,			_UpperCAmelCase=19    ,			_UpperCAmelCase=32    ,			_UpperCAmelCase=5    ,			_UpperCAmelCase=4    ,			_UpperCAmelCase=37    ,			_UpperCAmelCase="gelu"    ,			_UpperCAmelCase=0.1    ,			_UpperCAmelCase=0.1    ,			_UpperCAmelCase=512    ,			_UpperCAmelCase=16    ,			_UpperCAmelCase=2    ,			_UpperCAmelCase=0.02    ,			_UpperCAmelCase=3    ,			_UpperCAmelCase=4    ,			_UpperCAmelCase=None    ,			):
       lowercase__:   Optional[int]					=      parent
       lowercase__:   List[str]					=      batch_size
       lowercase__:   Dict					=      seq_length
       lowercase__:   Union[str, Any]					=      is_training
       lowercase__:   Dict					=      use_input_mask
       lowercase__:   Dict					=      use_token_type_ids
       lowercase__:   Optional[int]					=      use_labels
       lowercase__:   Tuple					=      vocab_size
       lowercase__:   Dict					=      hidden_size
       lowercase__:   Union[str, Any]					=      num_hidden_layers
       lowercase__:   Any					=      num_attention_heads
       lowercase__:   Tuple					=      intermediate_size
       lowercase__:   Tuple					=      hidden_act
       lowercase__:   int					=      hidden_dropout_prob
       lowercase__:   Tuple					=      attention_probs_dropout_prob
       lowercase__:   Optional[Any]					=      max_position_embeddings
       lowercase__:   Tuple					=      type_vocab_size
       lowercase__:   List[str]					=      type_sequence_label_size
       lowercase__:   Optional[Any]					=      initializer_range
       lowercase__:   Any					=      num_labels
       lowercase__:   Optional[Any]					=      num_choices
       lowercase__:   List[Any]					=      scope






    def _snake_case			(   self							):
       lowercase__:   Any					=      ids_tensor([self.batch_size, self.seq_length]    ,			self.vocab_size							)

       lowercase__:   Dict					=      None
       if self.use_input_mask:
          lowercase__:   List[str]					=      random_attention_mask([self.batch_size, self.seq_length]							)

       lowercase__:   Any					=      None
       lowercase__:   Tuple					=      None
       lowercase__:   List[Any]					=      None
       if self.use_labels:
          lowercase__:   Optional[int]					=      ids_tensor([self.batch_size]    ,			self.type_sequence_label_size							)
          lowercase__:   Union[str, Any]					=      ids_tensor([self.batch_size, self.seq_length]    ,			self.num_labels							)
          lowercase__:   Union[str, Any]					=      ids_tensor([self.batch_size]    ,			self.num_choices							)

       lowercase__:   int					=      self.get_config()

       return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






    def _snake_case			(   self							):
       lowercase__:   Optional[Any]					=      EsmConfig(
           vocab_size=33    ,			hidden_size=self.hidden_size    ,			pad_token_id=1    ,			num_hidden_layers=self.num_hidden_layers    ,			num_attention_heads=self.num_attention_heads    ,			intermediate_size=self.intermediate_size    ,			hidden_act=self.hidden_act    ,			hidden_dropout_prob=self.hidden_dropout_prob    ,			attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,			max_position_embeddings=self.max_position_embeddings    ,			type_vocab_size=self.type_vocab_size    ,			initializer_range=self.initializer_range    ,			is_folding_model=UpperCAmelCase__    ,			esmfold_config={'''trunk''': {'''num_blocks''': 2}, '''fp16_esm''': False}    ,			)
       return config






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   Any					=      EsmForProteinFolding(config=UpperCAmelCase__							).float()
       model.to(UpperCAmelCase__							)
       model.eval()
       lowercase__:   Any					=      model(UpperCAmelCase__    ,			attention_mask=UpperCAmelCase__							)
       lowercase__:   Optional[Any]					=      model(UpperCAmelCase__							)
       lowercase__:   Tuple					=      model(UpperCAmelCase__							)

       self.parent.assertEqual(result.positions.shape    ,			(8, self.batch_size, self.seq_length, 14, 3)							)
       self.parent.assertEqual(result.angles.shape    ,			(8, self.batch_size, self.seq_length, 7, 2)							)






    def _snake_case			(   self							):
       lowercase__:   Dict					=      self.prepare_config_and_inputs()
       (
           (
           lowercase__  
       ), (
           lowercase__  
       ), (
           lowercase__  
       ), (
           lowercase__  
       ), (
           lowercase__  
       ), (
           lowercase__  
       ),   
       ):   List[str]					=      config_and_inputs
       lowercase__:   List[Any]					=      {'''input_ids''': input_ids, '''attention_mask''': input_mask}
       return config, inputs_dict



@require_torch
class     UpperCAmelCase						(__lowercase    ,__lowercase    ,unittest.TestCase  ):



    """simple docstring"""

    _UpperCAmelCase	:str						    = False

    _UpperCAmelCase	:Union[str, Any]						    = (EsmForProteinFolding,) if is_torch_available() else ()
    _UpperCAmelCase	:Union[str, Any]						    = ()
    _UpperCAmelCase	:List[Any]						    = {} if is_torch_available() else {}
    _UpperCAmelCase	:Optional[Any]						    = False






    def _snake_case			(   self							):
       lowercase__:   int					=      EsmFoldModelTester(self							)
       lowercase__:   List[str]					=      ConfigTester(self    ,			config_class=UpperCAmelCase__    ,			hidden_size=37							)






    def _snake_case			(   self							):
       self.config_tester.run_common_tests()






    def _snake_case			(   self							):
       lowercase__:   Dict					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase__							)






    @unittest.skip('''Does not support attention outputs'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip
    def _snake_case			(   self							):
       pass






    @unittest.skip('''Esm does not support embedding resizing'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''Esm does not support embedding resizing'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support passing input embeds!'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support head pruning.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support head pruning.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support head pruning.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support head pruning.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support head pruning.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not output hidden states in the normal way.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMfold does not output hidden states in the normal way.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold only has one output format.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''This test doesn\'t work for ESMFold and doesn\'t test core functionality'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold does not support input chunking.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold doesn\'t support torchscript compilation.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold doesn\'t support torchscript compilation.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold doesn\'t support torchscript compilation.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''ESMFold doesn\'t support data parallel.'''							)
    def _snake_case			(   self							):
       pass






    @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''							)
    def _snake_case			(   self							):
       pass



@require_torch
class     UpperCAmelCase						(__lowercase  ):



    """simple docstring"""

    @slow
    def _snake_case			(   self							):
       lowercase__:   Dict					=      EsmForProteinFolding.from_pretrained('''facebook/esmfold_v1'''							).float()
       model.eval()
       lowercase__:   int					=      torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]							)
       lowercase__:   List[str]					=      model(UpperCAmelCase__							)['''positions''']
       lowercase__:   List[Any]					=      torch.tensor([2.5_828, 0.7_993, -10.9_334]    ,			dtype=torch.floataa							)
       self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0]    ,			UpperCAmelCase__    ,			atol=1e-4							)							)




'''simple docstring'''




from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


__snake_case    						="""\
@article{wang2019superglue,
  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
  author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},
  journal={arXiv preprint arXiv:1905.00537},
  year={2019}
}
"""

__snake_case    						="""\
SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after
GLUE with a new set of more difficult language understanding tasks, improved
resources, and a new public leaderboard.
"""

__snake_case    						="""
Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset.
Args:
    predictions: list of predictions to score. Depending on the SuperGlUE subset:
        - for 'record': list of question-answer dictionaries with the following keys:
            - 'idx': index of the question as specified by the dataset
            - 'prediction_text': the predicted answer text
        - for 'multirc': list of question-answer dictionaries with the following keys:
            - 'idx': index of the question-answer pair as specified by the dataset
            - 'prediction': the predicted answer label
        - otherwise: list of predicted labels
    references: list of reference labels. Depending on the SuperGLUE subset:
        - for 'record': list of question-answers dictionaries with the following keys:
            - 'idx': index of the question as specified by the dataset
            - 'answers': list of possible answers
        - otherwise: list of reference labels
Returns: depending on the SuperGLUE subset:
    - for 'record':
        - 'exact_match': Exact match between answer and gold answer
        - 'f1': F1 score
    - for 'multirc':
        - 'exact_match': Exact match between answer and gold answer
        - 'f1_m': Per-question macro-F1 score
        - 'f1_a': Average F1 score over all answers
    - for 'axb':
        'matthews_correlation': Matthew Correlation
    - for 'cb':
        - 'accuracy': Accuracy
        - 'f1': F1 score
    - for all others:
        - 'accuracy': Accuracy
Examples:

    >>> super_glue_metric = datasets.load_metric('super_glue', 'copa')  # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0, 'f1': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'record')
    >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]
    >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 1.0, 'f1': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')
    >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'matthews_correlation': 1.0}
"""





def 	a_					( lowerCamelCase	:     str	, lowerCamelCase	:     Union[str, Any]				):
   return float((preds == labels).mean()				)





def 	a_					( lowerCamelCase	:     Union[str, Any]	, lowerCamelCase	:     Dict	, lowerCamelCase	:     str="binary"				):
   lowerCAmelCase     =			simple_accuracy(lowerCamelCase	, lowerCamelCase				)
   lowerCAmelCase     =			float(fa_score(y_true=lowerCamelCase	, y_pred=lowerCamelCase	, average=lowerCamelCase				)				)
   return {
       "accuracy": acc,
       "f1": fa,
   }





def 	a_					( lowerCamelCase	:     List[Any]	, lowerCamelCase	:     List[Any]				):
   lowerCAmelCase     =			{}
   for id_pred, label in zip(lowerCamelCase	, lowerCamelCase				):
      lowerCAmelCase     =			f'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}'''
      lowerCAmelCase     =			id_pred['prediction']
      if question_id in question_map:
         question_map[question_id].append((pred, label)				)
      else:
         lowerCAmelCase     =			[(pred, label)]
   lowerCAmelCase     ,  lowerCAmelCase     =			[], []
   for question, preds_labels in question_map.items():
      lowerCAmelCase     ,  lowerCAmelCase     =			zip(*lowerCamelCase				)
      lowerCAmelCase     =			fa_score(y_true=lowerCamelCase	, y_pred=lowerCamelCase	, average='macro'				)
      fas.append(lowerCamelCase				)
      lowerCAmelCase     =			int(sum(pred == label for pred, label in preds_labels				) == len(lowerCamelCase				)				)
      ems.append(lowerCamelCase				)
   lowerCAmelCase     =			float(sum(lowerCamelCase				) / len(lowerCamelCase				)				)
   lowerCAmelCase     =			sum(lowerCamelCase				) / len(lowerCamelCase				)
   lowerCAmelCase     =			float(fa_score(y_true=lowerCamelCase	, y_pred=[id_pred['prediction'] for id_pred in ids_preds]				)				)
   return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a}




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





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  List[Any]:
        if self.config_name not in [
            "boolq",
            "cb",
            "copa",
            "multirc",
            "record",
            "rte",
            "wic",
            "wsc",
            "wsc.fixed",
            "axb",
            "axg",
        ]:
           raise KeyError(
               'You should supply a configuration name selected in '
               '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]'    )
        return datasets.MetricInfo(
            description=_DESCRIPTION    ,      citation=_CITATION    ,      inputs_description=_KWARGS_DESCRIPTION    ,      features=datasets.Features(self._get_feature_types()    )    ,      codebase_urls=[]    ,      reference_urls=[]    ,      format='numpy' if not self.config_name == 'record' and not self.config_name == 'multirc' else None    ,      )





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  str:
        if self.config_name == "record":
           return {
               "predictions": {
                   "idx": {
                       "passage": datasets.Value('int64'    ),
                       "query": datasets.Value('int64'    ),
                   },
                   "prediction_text": datasets.Value('string'    ),
               },
               "references": {
                   "idx": {
                       "passage": datasets.Value('int64'    ),
                       "query": datasets.Value('int64'    ),
                   },
                   "answers": datasets.Sequence(datasets.Value('string'    )    ),
               },
           }
        elif self.config_name == "multirc":
           return {
               "predictions": {
                   "idx": {
                       "answer": datasets.Value('int64'    ),
                       "paragraph": datasets.Value('int64'    ),
                       "question": datasets.Value('int64'    ),
                   },
                   "prediction": datasets.Value('int64'    ),
               },
               "references": datasets.Value('int64'    ),
           }
        else:
           return {
               "predictions": datasets.Value('int64'    ),
               "references": datasets.Value('int64'    ),
           }





     def 							__UpperCAmelCase      ( self       :      List[str]    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Optional[Any]    )				->  Any:
        if self.config_name == "axb":
           return {"matthews_correlation": matthews_corrcoef(UpperCAmelCase__    ,      UpperCAmelCase__    )}
        elif self.config_name == "cb":
           return acc_and_fa(UpperCAmelCase__    ,      UpperCAmelCase__    ,      fa_avg='macro'    )
        elif self.config_name == "record":
           lowerCAmelCase     =			[
               {
                   'qas': [
                       {'id': ref['idx']['query'], 'answers': [{'text': ans} for ans in ref['answers']]}
                       for ref in references
                   ]
               }
           ]
           lowerCAmelCase     =			{pred['idx']['query']: pred['prediction_text'] for pred in predictions}
           return evaluate_record(UpperCAmelCase__    ,      UpperCAmelCase__    )[0]
        elif self.config_name == "multirc":
           return evaluate_multirc(UpperCAmelCase__    ,      UpperCAmelCase__    )
        elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
           return {"accuracy": simple_accuracy(UpperCAmelCase__    ,      UpperCAmelCase__    )}
        else:
           raise KeyError(
               'You should supply a configuration name selected in '
               '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]'    )





