
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 import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
     from transformers.models.esm.modeling_esm import (
         ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
         EsmEmbeddings,
         create_position_ids_from_input_ids,
     )



class       _snake_case   :


 def __init__(					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=13					,  SCREAMING_SNAKE_CASE_=7					,  SCREAMING_SNAKE_CASE_=False					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=False					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=33					,  SCREAMING_SNAKE_CASE_=32					,  SCREAMING_SNAKE_CASE_=5					,  SCREAMING_SNAKE_CASE_=4					,  SCREAMING_SNAKE_CASE_=37					,  SCREAMING_SNAKE_CASE_="gelu"					,  SCREAMING_SNAKE_CASE_=0.1					,  SCREAMING_SNAKE_CASE_=0.1					,  SCREAMING_SNAKE_CASE_=5_12					,  SCREAMING_SNAKE_CASE_=16					,  SCREAMING_SNAKE_CASE_=2					,  SCREAMING_SNAKE_CASE_=0.0_2					,  SCREAMING_SNAKE_CASE_=3					,  SCREAMING_SNAKE_CASE_=4					,  SCREAMING_SNAKE_CASE_=None					,  ):


   '''simple docstring'''




   lowercase__  :   Union[str, Any]    		=      parent
   lowercase__  :   Tuple    		=      batch_size
   lowercase__  :   List[str]    		=      seq_length
   lowercase__  :   str    		=      is_training
   lowercase__  :   Dict    		=      use_input_mask
   lowercase__  :   Dict    		=      use_token_type_ids
   lowercase__  :   Optional[int]    		=      use_labels
   lowercase__  :   int    		=      vocab_size
   lowercase__  :   Any    		=      hidden_size
   lowercase__  :   str    		=      num_hidden_layers
   lowercase__  :   int    		=      num_attention_heads
   lowercase__  :   List[str]    		=      intermediate_size
   lowercase__  :   Optional[int]    		=      hidden_act
   lowercase__  :   Union[str, Any]    		=      hidden_dropout_prob
   lowercase__  :   Dict    		=      attention_probs_dropout_prob
   lowercase__  :   Dict    		=      max_position_embeddings
   lowercase__  :   Union[str, Any]    		=      type_vocab_size
   lowercase__  :   List[str]    		=      type_sequence_label_size
   lowercase__  :   Tuple    		=      initializer_range
   lowercase__  :   List[Any]    		=      num_labels
   lowercase__  :   str    		=      num_choices
   lowercase__  :   List[str]    		=      scope


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size)

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

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

   lowercase__  :   Union[str, Any]    		=      self.get_config()

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


 def      lowercase__     (					self):


   '''simple docstring'''




   return EsmConfig(
       vocab_size=self.vocab_size					,  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					,  )


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Union[str, Any]    		=      EsmModel(config=SCREAMING_SNAKE_CASE_)
   model.to(SCREAMING_SNAKE_CASE_)
   model.eval()
   lowercase__  :   Union[str, Any]    		=      model(SCREAMING_SNAKE_CASE_					,  attention_mask=SCREAMING_SNAKE_CASE_)
   lowercase__  :   Union[str, Any]    		=      model(SCREAMING_SNAKE_CASE_)
   lowercase__  :   str    		=      model(SCREAMING_SNAKE_CASE_)

   self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size))
   self.parent.assertEqual(result.pooler_output.shape					,  (self.batch_size, self.hidden_size))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_)
   model.to(SCREAMING_SNAKE_CASE_)
   model.eval()
   lowercase__  :   Optional[int]    		=      model(SCREAMING_SNAKE_CASE_					,  attention_mask=SCREAMING_SNAKE_CASE_					,  labels=SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.vocab_size))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   str    		=      self.num_labels
   lowercase__  :   Tuple    		=      EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_)
   model.to(SCREAMING_SNAKE_CASE_)
   model.eval()
   lowercase__  :   Optional[int]    		=      model(SCREAMING_SNAKE_CASE_					,  attention_mask=SCREAMING_SNAKE_CASE_					,  labels=SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.num_labels))



 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Dict    		=      self.prepare_config_and_inputs()
   (
       (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    
   )  :   Union[str, Any]    		=      config_and_inputs
   lowercase__  :   Optional[int]    		=      {"""input_ids""": input_ids, """attention_mask""": input_mask}
   return config, inputs_dict



@require_torch
class       _snake_case   (	UpperCAmelCase_  ,						UpperCAmelCase_  ,						unittest.TestCase							):
 __lowerCAmelCase  :     List[str]        =			False

 __lowerCAmelCase  :     str        =			(
     (
         EsmForMaskedLM,
         EsmModel,
         EsmForSequenceClassification,
         EsmForTokenClassification,
     )
     if is_torch_available()
     else ()
 )
 __lowerCAmelCase  :     Any        =			()
 __lowerCAmelCase  :     List[Any]        =			(
     {
         'feature-extraction': EsmModel,
         'fill-mask': EsmForMaskedLM,
         'text-classification': EsmForSequenceClassification,
         'token-classification': EsmForTokenClassification,
         'zero-shot': EsmForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowerCAmelCase  :     Optional[Any]        =			True


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      EsmModelTester(self)
   lowercase__  :   List[Any]    		=      ConfigTester(self					,  config_class=SCREAMING_SNAKE_CASE_					,  hidden_size=37)


 def      lowercase__     (					self):


   '''simple docstring'''




   self.config_tester.run_common_tests()


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[Any]    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      self.model_tester.prepare_config_and_inputs()
   for type in ["absolute", "relative_key", "relative_key_query"]:
     lowercase__  :   List[Any]    		=      type
     self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Any    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_)


 @slow
 def      lowercase__     (					self):


   '''simple docstring'''




   for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowercase__  :   Dict    		=      EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_)
     self.assertIsNotNone(SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Any    		=      self.model_tester.prepare_config_and_inputs()[0]
   lowercase__  :   Dict    		=      EsmEmbeddings(config=SCREAMING_SNAKE_CASE_)

   lowercase__  :   Dict    		=      torch.as_tensor([[12, 31, 13, model.padding_idx]])
   lowercase__  :   Union[str, Any]    		=      torch.as_tensor(
       [
           [
               0 + model.padding_idx + 1,
               1 + model.padding_idx + 1,
               2 + model.padding_idx + 1,
               model.padding_idx,
           ]
       ])
   lowercase__  :   Optional[Any]    		=      create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_					,  model.padding_idx)
   self.assertEqual(position_ids.shape					,  expected_positions.shape)
   self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_)))


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[Any]    		=      self.model_tester.prepare_config_and_inputs()[0]
   lowercase__  :   int    		=      EsmEmbeddings(config=SCREAMING_SNAKE_CASE_)

   lowercase__  :   Optional[int]    		=      torch.empty(2					,  4					,  30)
   lowercase__  :   List[Any]    		=      [
       0 + embeddings.padding_idx + 1,
       1 + embeddings.padding_idx + 1,
       2 + embeddings.padding_idx + 1,
       3 + embeddings.padding_idx + 1,
   ]
   lowercase__  :   Dict    		=      torch.as_tensor([expected_single_positions, expected_single_positions])
   lowercase__  :   List[str]    		=      embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_)
   self.assertEqual(position_ids.shape					,  expected_positions.shape)
   self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_)))


 @unittest.skip("""Esm does not support embedding resizing""")
 def      lowercase__     (					self):


   '''simple docstring'''




   pass


 @unittest.skip("""Esm does not support embedding resizing""")
 def      lowercase__     (					self):


   '''simple docstring'''




   pass



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


   '''simple docstring'''




   pass



@require_torch
class       _snake_case   (	UpperCAmelCase_							):


 @slow
 def      lowercase__     (					self):


   '''simple docstring'''




   with torch.no_grad():
     lowercase__  :   str    		=      EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""")
     model.eval()
     lowercase__  :   Dict    		=      torch.tensor([[0, 1, 2, 3, 4, 5]])
     lowercase__  :   Optional[int]    		=      model(SCREAMING_SNAKE_CASE_)[0]

     lowercase__  :   Any    		=      33

     lowercase__  :   List[str]    		=      torch.Size((1, 6, vocab_size))
     self.assertEqual(output.shape					,  SCREAMING_SNAKE_CASE_)

     lowercase__  :   Optional[int]    		=      torch.tensor(
         [[[8.9_2_1_5, -1_0.5_8_9_8, -6.4_6_7_1], [-6.3_9_6_7, -1_3.9_1_1_4, -1.1_2_1_2], [-7.7_8_1_2, -1_3.9_5_1_6, -3.7_4_0_6]]])
     self.assertTrue(torch.allclose(output[:, :3, :3]					,  SCREAMING_SNAKE_CASE_					,  atol=1E-4))



 @slow
 def      lowercase__     (					self):


   '''simple docstring'''




   with torch.no_grad():
     lowercase__  :   str    		=      EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""")
     model.eval()

     lowercase__  :   Optional[int]    		=      torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
     lowercase__  :   str    		=      model(SCREAMING_SNAKE_CASE_)[0]
     # compare the actual values for a slice.
     lowercase__  :   Optional[int]    		=      torch.tensor(
         [[[0.1_4_4_4, 0.5_4_1_3, 0.3_2_4_8], [0.3_0_3_4, 0.0_0_5_3, 0.3_1_0_8], [0.3_2_2_8, -0.2_4_9_9, 0.3_4_1_5]]])
     self.assertTrue(torch.allclose(output[:, :3, :3]					,  SCREAMING_SNAKE_CASE_					,  atol=1E-4))








from scipy.stats import spearmanr

import datasets


lowerCamelCase__    :		Union[str, Any]          =   """
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

lowerCamelCase__    :		int          =   """
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

lowerCamelCase__    :		str          =   R"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
"""



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


 def      lowercase__     (					self):


   '''simple docstring'''




   return datasets.MetricInfo(
       description=_DESCRIPTION					,  citation=_CITATION					,  inputs_description=_KWARGS_DESCRIPTION					,  features=datasets.Features(
           {
               """predictions""": datasets.Value("""float"""),
               """references""": datasets.Value("""float"""),
           })					,  reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""]					,  )



 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=False):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      spearmanr(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_)
   if return_pvalue:
     return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
   else:
     return {"spearmanr": results[0]}






