






import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
    from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor



class  A__       :





      def __init__(			self	,							A_	,							A_=13	,							A_=32	,							A_=3	,							A_=4	,							A_=[10, 20, 30, 40]	,							A_=[2, 2, 3, 2]	,							A_=True	,							A_=True	,							A_=37	,							A_="gelu"	,							A_=10	,							A_=0.02	,							A_=["stage2", "stage3", "stage4"]	,							A_=[2, 3, 4]	,							A_=None	,							):
       '''simple docstring'''




       UpperCamelCase     : Any	     =       parent
       UpperCamelCase     : Optional[Any]	     =       batch_size
       UpperCamelCase     : Dict	     =       image_size
       UpperCamelCase     : Optional[Any]	     =       num_channels
       UpperCamelCase     : Tuple	     =       num_stages
       UpperCamelCase     : Dict	     =       hidden_sizes
       UpperCamelCase     : Union[str, Any]	     =       depths
       UpperCamelCase     : Optional[Any]	     =       is_training
       UpperCamelCase     : str	     =       use_labels
       UpperCamelCase     : List[Any]	     =       intermediate_size
       UpperCamelCase     : int	     =       hidden_act
       UpperCamelCase     : Optional[int]	     =       num_labels
       UpperCamelCase     : Union[str, Any]	     =       initializer_range
       UpperCamelCase     : int	     =       out_features
       UpperCamelCase     : Tuple	     =       out_indices
       UpperCamelCase     : Union[str, Any]	     =       scope





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

       UpperCamelCase     : Tuple	     =       None
       if self.use_labels:
        UpperCamelCase     : List[str]	     =       ids_tensor([self.batch_size]	,							self.num_labels       )

       UpperCamelCase     : Union[str, Any]	     =       self.get_config()
       return config, pixel_values, labels





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return ConvNextConfig(
           num_channels=self.num_channels	,							hidden_sizes=self.hidden_sizes	,							depths=self.depths	,							num_stages=self.num_stages	,							hidden_act=self.hidden_act	,							is_decoder=A_	,							initializer_range=self.initializer_range	,							out_features=self.out_features	,							out_indices=self.out_indices	,							num_labels=self.num_labels	,							)





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       ConvNextModel(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : List[Any]	     =       model(A_       )
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape	,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)	,							)





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       ConvNextForImageClassification(A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : List[Any]	     =       model(A_	,							labels=A_       )
       self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.num_labels)       )





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       ConvNextBackbone(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : Tuple	     =       model(A_       )

       # verify hidden states
       self.parent.assertEqual(len(result.feature_maps       )	,							len(config.out_features       )       )
       self.parent.assertListEqual(list(result.feature_maps[0].shape       )	,							[self.batch_size, self.hidden_sizes[1], 4, 4]       )

       # verify channels
       self.parent.assertEqual(len(model.channels       )	,							len(config.out_features       )       )
       self.parent.assertListEqual(model.channels	,							config.hidden_sizes[1:]       )

       # verify backbone works with out_features=None
       UpperCamelCase     : Optional[int]	     =       None
       UpperCamelCase     : Dict	     =       ConvNextBackbone(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : int	     =       model(A_       )

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps       )	,							1       )
       self.parent.assertListEqual(list(result.feature_maps[0].shape       )	,							[self.batch_size, self.hidden_sizes[-1], 1, 1]       )

       # verify channels
       self.parent.assertEqual(len(model.channels       )	,							1       )
       self.parent.assertListEqual(model.channels	,							[config.hidden_sizes[-1]]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       self.prepare_config_and_inputs()
       UpperCamelCase     : Dict	     =       config_and_inputs
       UpperCamelCase     : List[str]	     =       {"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class  A__       (	__snake_case	,       __snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :Dict						   =       (
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      _UpperCAmelCase     :Any						   =       (
          {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      _UpperCAmelCase     :List[str]						   =       True
      _UpperCAmelCase     :int						   =       False
      _UpperCAmelCase     :int						   =       False
      _UpperCAmelCase     :Optional[Any]						   =       False
      _UpperCAmelCase     :Union[str, Any]						   =       False





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       ConvNextModelTester(self       )
       UpperCamelCase     : Optional[Any]	     =       ConfigTester(self	,							config_class=A_	,							has_text_modality=A_	,							hidden_size=37       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       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 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return





      @unittest.skip(reason="ConvNext does not use inputs_embeds"       )
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="ConvNext does not support input and output embeddings"       )
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="ConvNext does not use feedforward chunking"       )
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase     : Any	     =       ["pixel_values"]
        self.assertListEqual(arg_names[:1]	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Any	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       def check_hidden_states_output(A_	,							A_	,							A_       ):
        UpperCamelCase     : Any	     =       model_class(A_       )
        model.to(A_       )
        model.eval()

        with torch.no_grad():
         UpperCamelCase     : Union[str, Any]	     =       model(**self._prepare_for_class(A_	,							A_       )       )

        UpperCamelCase     : Dict	     =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        UpperCamelCase     : List[str]	     =       self.model_tester.num_stages
        self.assertEqual(len(A_       )	,							expected_num_stages + 1       )

        # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
        self.assertListEqual(
            list(hidden_states[0].shape[-2:]       )	,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]	,							)

       UpperCamelCase     : Tuple	     =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase     : Any	     =       True
        check_hidden_states_output(A_	,							A_	,							A_       )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        UpperCamelCase     : Optional[int]	     =       True

        check_hidden_states_output(A_	,							A_	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_       )





      @slow
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase     : int	     =       ConvNextModel.from_pretrained(A_       )
        self.assertIsNotNone(A_       )



def 		A_    (					)						->			Dict:
 UpperCamelCase     : int	     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
 return image



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





      @cached_property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"       ) if is_vision_available() else None





      @slow
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"       ).to(A_       )

       UpperCamelCase     : Tuple	     =       self.default_image_processor
       UpperCamelCase     : int	     =       prepare_img()
       UpperCamelCase     : Dict	     =       image_processor(images=A_	,							return_tensors="pt"       ).to(A_       )

       # forward pass
       with torch.no_grad():
        UpperCamelCase     : List[str]	     =       model(**A_       )

       # verify the logits
       UpperCamelCase     : Tuple	     =       torch.Size((1, 1000)       )
       self.assertEqual(outputs.logits.shape	,							A_       )

       UpperCamelCase     : List[str]	     =       torch.tensor([-0.02_60, -0.47_39, 0.19_11]       ).to(A_       )

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



@require_torch
class  A__       (	unittest.TestCase	,       __snake_case      ):
      _UpperCAmelCase     :Optional[Any]						   =       (ConvNextBackbone,) if is_torch_available() else ()
      _UpperCAmelCase     :Optional[int]						   =       ConvNextConfig

      _UpperCAmelCase     :Tuple						   =       False





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       ConvNextModelTester(self       )







from scipy.stats import spearmanr

import datasets


__lowerCamelCase	:					List[str]			  =					"""
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	:					List[Any]			  =					"""
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	:					Optional[int]			  =					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  A__       (	datasets.Metric      ):





      def 	__UpperCamelCase(			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 	__UpperCamelCase(			self	,							A_	,							A_	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : Tuple	     =       spearmanr(A_	,							A_       )
       if return_pvalue:
        return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
       else:
        return {"spearmanr": results[0]}
