

'''simple docstring'''






from scipy.stats import spearmanr

import datasets


lowerCAmelCase__      		=			'''
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__      		=			'''
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__      		=			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     lowercase_			(datasets.Metric   ):




       """simple docstring"""




       def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
        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       SCREAMING_SNAKE_CASE   (   self     :  Tuple      ,lowercase__     :  List[Any]      ,lowercase__     :  List[Any]      ,lowercase__     :  Union[str, Any]=False    ):
        __lowercase													=				spearmanr(lowercase__      ,lowercase__    )
        if return_pvalue:
         return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
        else:
         return {"spearmanr": results[0]}




'''simple docstring'''






import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
 import torch

 from transformers import CvtForImageClassification, CvtModel
 from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor






class     lowercase_			(lowerCamelCase__   ):




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   __lowercase													=				self.config_class(**self.inputs_dict    )
   self.parent.assertTrue(hasattr(lowercase__      ,'''embed_dim'''    )    )
   self.parent.assertTrue(hasattr(lowercase__      ,'''num_heads'''    )    )






class     lowercase_			:




  """simple docstring"""




  def __init__(   self     :  Optional[Any]      ,lowercase__     :  Optional[int]      ,lowercase__     :  Optional[int]=1_3      ,lowercase__     :  List[Any]=6_4      ,lowercase__     :  Optional[int]=3      ,lowercase__     :  Dict=[1_6, 4_8, 9_6]      ,lowercase__     :  Optional[Any]=[1, 3, 6]      ,lowercase__     :  Tuple=[1, 2, 1_0]      ,lowercase__     :  Optional[int]=[7, 3, 3]      ,lowercase__     :  str=[4, 2, 2]      ,lowercase__     :  Dict=[2, 1, 1]      ,lowercase__     :  Tuple=[2, 2, 2]      ,lowercase__     :  Tuple=[False, False, True]      ,lowercase__     :  int=[0.0, 0.0, 0.0]      ,lowercase__     :  str=0.0_2      ,lowercase__     :  Union[str, Any]=1e-1_2      ,lowercase__     :  Optional[int]=True      ,lowercase__     :  Union[str, Any]=True      ,lowercase__     :  Optional[Any]=2      ,):
   __lowercase													=				parent
   __lowercase													=				batch_size
   __lowercase													=				image_size
   __lowercase													=				patch_sizes
   __lowercase													=				patch_stride
   __lowercase													=				patch_padding
   __lowercase													=				is_training
   __lowercase													=				use_labels
   __lowercase													=				num_labels
   __lowercase													=				num_channels
   __lowercase													=				embed_dim
   __lowercase													=				num_heads
   __lowercase													=				stride_kv
   __lowercase													=				depth
   __lowercase													=				cls_token
   __lowercase													=				attention_drop_rate
   __lowercase													=				initializer_range
   __lowercase													=				layer_norm_eps






  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase													=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

   __lowercase													=				None
   if self.use_labels:
    __lowercase													=				ids_tensor([self.batch_size]      ,self.num_labels    )

   __lowercase													=				self.get_config()
   return config, pixel_values, labels






  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   return CvtConfig(
       image_size=self.image_size      ,num_labels=self.num_labels      ,num_channels=self.num_channels      ,embed_dim=self.embed_dim      ,num_heads=self.num_heads      ,patch_sizes=self.patch_sizes      ,patch_padding=self.patch_padding      ,patch_stride=self.patch_stride      ,stride_kv=self.stride_kv      ,depth=self.depth      ,cls_token=self.cls_token      ,attention_drop_rate=self.attention_drop_rate      ,initializer_range=self.initializer_range      ,)






  def       SCREAMING_SNAKE_CASE   (   self     :  Dict      ,lowercase__     :  List[str]      ,lowercase__     :  Any      ,lowercase__     :  List[str]    ):
   __lowercase													=				CvtModel(config=lowercase__    )
   model.to(lowercase__    )
   model.eval()
   __lowercase													=				model(lowercase__    )
   __lowercase													=				(self.image_size, self.image_size)
   __lowercase						,			__lowercase													=				image_size[0], image_size[1]
   for i in range(len(self.depth    )    ):
    __lowercase													=				floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
    __lowercase													=				floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
   self.parent.assertEqual(result.last_hidden_state.shape      ,(self.batch_size, self.embed_dim[-1], height, width)    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Dict      ,lowercase__     :  Any      ,lowercase__     :  List[Any]      ,lowercase__     :  Dict    ):
   __lowercase													=				self.num_labels
   __lowercase													=				CvtForImageClassification(lowercase__    )
   model.to(lowercase__    )
   model.eval()
   __lowercase													=				model(lowercase__      ,labels=lowercase__    )
   self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.num_labels)    )






  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase													=				self.prepare_config_and_inputs()
   __lowercase						,			__lowercase						,			__lowercase													=				config_and_inputs
   __lowercase													=				{'''pixel_values''': pixel_values}
   return config, inputs_dict






@require_torch
class     lowercase_			(lowerCamelCase__       , lowerCamelCase__       , unittest.TestCase   ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						Any           =    (CvtModel, CvtForImageClassification) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE					:						Optional[int]           =    (
      {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE					:						Optional[int]           =    False
  SCREAMING_SNAKE_CASE					:						Union[str, Any]           =    False
  SCREAMING_SNAKE_CASE					:						int           =    False
  SCREAMING_SNAKE_CASE					:						Optional[Any]           =    False
  SCREAMING_SNAKE_CASE					:						str           =    False






  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase													=				CvtModelTester(self    )
   __lowercase													=				ConfigTester(self      ,config_class=lowercase__      ,has_text_modality=lowercase__      ,hidden_size=3_7    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   self.create_and_test_config_common_properties()
   self.config_tester.create_and_test_config_to_json_string()
   self.config_tester.create_and_test_config_to_json_file()
   self.config_tester.create_and_test_config_from_and_save_pretrained()
   self.config_tester.create_and_test_config_with_num_labels()
   self.config_tester.check_config_can_be_init_without_params()
   self.config_tester.check_config_arguments_init()






  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   return






  @unittest.skip(reason='''Cvt does not output attentions'''    )
  def       SCREAMING_SNAKE_CASE   (   self     :  Any    ):
   pass






  @unittest.skip(reason='''Cvt does not use inputs_embeds'''    )
  def       SCREAMING_SNAKE_CASE   (   self     :  Any    ):
   pass






  @unittest.skip(reason='''Cvt does not support input and output embeddings'''    )
  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   pass






  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase						,			__lowercase													=				self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    __lowercase													=				model_class(lowercase__    )
    __lowercase													=				inspect.signature(model.forward    )
    # signature.parameters is an OrderedDict => so arg_names order is deterministic
    __lowercase													=				[*signature.parameters.keys()]

    __lowercase													=				['''pixel_values''']
    self.assertListEqual(arg_names[:1]      ,lowercase__    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   __lowercase													=				self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowercase__    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Tuple    ):
   def check_hidden_states_output(lowercase__     :  Union[str, Any]      ,lowercase__     :  Union[str, Any]      ,lowercase__     :  str    ):
    __lowercase													=				model_class(lowercase__    )
    model.to(lowercase__    )
    model.eval()

    with torch.no_grad():
     __lowercase													=				model(**self._prepare_for_class(lowercase__      ,lowercase__    )    )

    __lowercase													=				outputs.hidden_states

    __lowercase													=				len(self.model_tester.depth    )
    self.assertEqual(len(lowercase__    )      ,lowercase__    )

    # verify the first hidden states (first block)
    self.assertListEqual(
        list(hidden_states[0].shape[-3:]    )      ,[
            self.model_tester.embed_dim[0],
            self.model_tester.image_size // 4,
            self.model_tester.image_size // 4,
        ]      ,)

   __lowercase						,			__lowercase													=				self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    __lowercase													=				True
    check_hidden_states_output(lowercase__      ,lowercase__      ,lowercase__    )

    # check that output_hidden_states also work using config
    del inputs_dict["output_hidden_states"]
    __lowercase													=				True

    check_hidden_states_output(lowercase__      ,lowercase__      ,lowercase__    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Dict    ):
   __lowercase													=				self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowercase__    )






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






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __lowercase													=				CvtModel.from_pretrained(lowercase__    )
    self.assertIsNotNone(lowercase__    )


def 	_A  (					):






 """simple docstring"""



 __lowercase													=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
 return image






@require_torch
@require_vision
class     lowercase_			(unittest.TestCase   ):




  """simple docstring"""




  @cached_property
  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[Any]    ):
   return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase													=				CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(lowercase__    )

   __lowercase													=				self.default_image_processor
   __lowercase													=				prepare_img()
   __lowercase													=				image_processor(images=lowercase__      ,return_tensors='''pt'''    ).to(lowercase__    )

   # forward pass
   with torch.no_grad():
    __lowercase													=				model(**lowercase__    )

   # verify the logits
   __lowercase													=				torch.Size((1, 1_0_0_0)    )
   self.assertEqual(outputs.logits.shape      ,lowercase__    )

   __lowercase													=				torch.tensor([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]    ).to(lowercase__    )

   self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,lowercase__      ,atol=1e-4    )    )

