


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     a		(_lowerCAmelCase				):




							"""simple docstring"""


							def    __snake_case (							self	:  Optional[Any]    )     ->   int:
														__snake_case		:      Optional[int]										=       self.config_class(**self.inputs_dict    )
														self.parent.assertTrue(hasattr(lowerCamelCase   ,     "embed_dim"    )    )
														self.parent.assertTrue(hasattr(lowerCamelCase   ,     "num_heads"    )    )

class     a		:




							"""simple docstring"""


							def __init__(							self	:  Union[str, Any]   ,     lowerCamelCase	:  List[Any]   ,     lowerCamelCase	:  Dict=13   ,     lowerCamelCase	:  str=64   ,     lowerCamelCase	:  Tuple=3   ,     lowerCamelCase	:  List[str]=[16, 48, 96]   ,     lowerCamelCase	:  Tuple=[1, 3, 6]   ,     lowerCamelCase	:  Any=[1, 2, 10]   ,     lowerCamelCase	:  List[Any]=[7, 3, 3]   ,     lowerCamelCase	:  Tuple=[4, 2, 2]   ,     lowerCamelCase	:  Tuple=[2, 1, 1]   ,     lowerCamelCase	:  int=[2, 2, 2]   ,     lowerCamelCase	:  Dict=[False, False, True]   ,     lowerCamelCase	:  List[Any]=[0.0, 0.0, 0.0]   ,     lowerCamelCase	:  Union[str, Any]=0.02   ,     lowerCamelCase	:  Tuple=1E-12   ,     lowerCamelCase	:  int=True   ,     lowerCamelCase	:  int=True   ,     lowerCamelCase	:  Union[str, Any]=2   ,     )     ->   Dict:
														__snake_case		:      List[str]										=       parent
														__snake_case		:      List[str]										=       batch_size
														__snake_case		:      str										=       image_size
														__snake_case		:      Union[str, Any]										=       patch_sizes
														__snake_case		:      Optional[int]										=       patch_stride
														__snake_case		:      Dict										=       patch_padding
														__snake_case		:      List[str]										=       is_training
														__snake_case		:      Optional[Any]										=       use_labels
														__snake_case		:      Tuple										=       num_labels
														__snake_case		:      Dict										=       num_channels
														__snake_case		:      Union[str, Any]										=       embed_dim
														__snake_case		:      int										=       num_heads
														__snake_case		:      Optional[Any]										=       stride_kv
														__snake_case		:      Tuple										=       depth
														__snake_case		:      Optional[Any]										=       cls_token
														__snake_case		:      Dict										=       attention_drop_rate
														__snake_case		:      Optional[int]										=       initializer_range
														__snake_case		:      Any										=       layer_norm_eps

							def    __snake_case (							self	:  List[Any]    )     ->   Dict:
														__snake_case		:      List[str]										=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

														__snake_case		:      Union[str, Any]										=       None
														if self.use_labels:
																					__snake_case		:      Any										=       ids_tensor([self.batch_size]   ,     self.num_labels    )

														__snake_case		:      Any										=       self.get_config()
														return config, pixel_values, labels

							def    __snake_case (							self	:  Any    )     ->   List[Any]:
														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    __snake_case (							self	:  Optional[Any]   ,     lowerCamelCase	:  List[Any]   ,     lowerCamelCase	:  Tuple   ,     lowerCamelCase	:  List[str]    )     ->   Union[str, Any]:
														__snake_case		:      str										=       CvtModel(config=lowerCamelCase    )
														model.to(lowerCamelCase    )
														model.eval()
														__snake_case		:      Tuple										=       model(lowerCamelCase    )
														__snake_case		:      Union[str, Any]										=       (self.image_size, self.image_size)
														__snake_case			,      __snake_case		:      List[Any]										=       image_size[0], image_size[1]
														for i in range(len(self.depth    )    ):
																					__snake_case		:      List[str]										=       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
																					__snake_case		:      str										=       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    __snake_case (							self	:  Tuple   ,     lowerCamelCase	:  Optional[int]   ,     lowerCamelCase	:  Dict   ,     lowerCamelCase	:  List[str]    )     ->   List[Any]:
														__snake_case		:      int										=       self.num_labels
														__snake_case		:      int										=       CvtForImageClassification(lowerCamelCase    )
														model.to(lowerCamelCase    )
														model.eval()
														__snake_case		:      Any										=       model(lowerCamelCase   ,     labels=lowerCamelCase    )
														self.parent.assertEqual(result.logits.shape   ,     (self.batch_size, self.num_labels)    )






							def    __snake_case (							self	:  int    )     ->   str:
														__snake_case		:      Tuple										=       self.prepare_config_and_inputs()
														__snake_case			,      __snake_case			,      __snake_case		:      str										=       config_and_inputs
														__snake_case		:      Optional[Any]										=       {"pixel_values": pixel_values}
														return config, inputs_dict

@require_torch
class     a		(_lowerCAmelCase					,    _lowerCAmelCase					,    unittest.TestCase				):




							"""simple docstring"""


							__UpperCAmelCase   :							Union[str, Any]					  =  (CvtModel, CvtForImageClassification) if is_torch_available() else ()
							__UpperCAmelCase   :							List[Any]					  =  (
							    {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
							    if is_torch_available()
							    else {}
							)

							__UpperCAmelCase   :							Optional[Any]					  =  False
							__UpperCAmelCase   :							Any					  =  False
							__UpperCAmelCase   :							Tuple					  =  False
							__UpperCAmelCase   :							Any					  =  False
							__UpperCAmelCase   :							int					  =  False

							def    __snake_case (							self	:  Union[str, Any]    )     ->   Optional[int]:
														__snake_case		:      Optional[Any]										=       CvtModelTester(self    )
														__snake_case		:      str										=       ConfigTester(self   ,     config_class=lowerCamelCase   ,     has_text_modality=lowerCamelCase   ,     hidden_size=37    )

							def    __snake_case (							self	:  List[str]    )     ->   int:
														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    __snake_case (							self	:  Tuple    )     ->   Optional[int]:
														return

							@unittest.skip(reason="Cvt does not output attentions"    )
							def    __snake_case (							self	:  Union[str, Any]    )     ->   Union[str, Any]:
														pass

							@unittest.skip(reason="Cvt does not use inputs_embeds"    )
							def    __snake_case (							self	:  Optional[Any]    )     ->   List[Any]:
														pass

							@unittest.skip(reason="Cvt does not support input and output embeddings"    )
							def    __snake_case (							self	:  int    )     ->   Union[str, Any]:
														pass

							def    __snake_case (							self	:  Union[str, Any]    )     ->   Optional[int]:
														__snake_case			,      __snake_case		:      Optional[int]										=       self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					__snake_case		:      Optional[Any]										=       model_class(lowerCamelCase    )
																					__snake_case		:      List[str]										=       inspect.signature(model.forward    )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					__snake_case		:      int										=       [*signature.parameters.keys()]

																					__snake_case		:      Any										=       ["pixel_values"]
																					self.assertListEqual(arg_names[:1]   ,     lowerCamelCase    )

							def    __snake_case (							self	:  Optional[Any]    )     ->   Dict:
														__snake_case		:      int										=       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*lowerCamelCase    )

							def    __snake_case (							self	:  Any    )     ->   Any:
														def check_hidden_states_output(lowerCamelCase	:  Dict   ,     lowerCamelCase	:  int   ,     lowerCamelCase	:  Dict    ):
																					__snake_case		:      Any										=       model_class(lowerCamelCase    )
																					model.to(lowerCamelCase    )
																					model.eval()

																					with torch.no_grad():
																												__snake_case		:      List[str]										=       model(**self._prepare_for_class(lowerCamelCase   ,     lowerCamelCase    )    )

																					__snake_case		:      str										=       outputs.hidden_states

																					__snake_case		:      List[str]										=       len(self.model_tester.depth    )
																					self.assertEqual(len(lowerCamelCase    )   ,     lowerCamelCase    )

																					# 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,
																					    ]   ,     )

														__snake_case			,      __snake_case		:      Dict										=       self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					__snake_case		:      List[Any]										=       True
																					check_hidden_states_output(lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase    )

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					__snake_case		:      List[str]										=       True

																					check_hidden_states_output(lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase    )

							def    __snake_case (							self	:  Dict    )     ->   str:
														__snake_case		:      List[Any]										=       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*lowerCamelCase    )

							@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."    )
							def    __snake_case (							self	:  Any    )     ->   Union[str, Any]:
														pass






							@slow
							def    __snake_case (							self	:  Optional[int]    )     ->   Tuple:
														for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					__snake_case		:      Dict										=       CvtModel.from_pretrained(lowerCamelCase    )
																					self.assertIsNotNone(lowerCamelCase    )







def     lowerCAmelCase_					( ):
							__snake_case		:      str										=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
							return image

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




							"""simple docstring"""


							@cached_property
							def    __snake_case (							self	:  str    )     ->   Optional[int]:
														return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )






							@slow
							def    __snake_case (							self	:  List[str]    )     ->   List[str]:
														__snake_case		:      List[str]										=       CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(lowerCamelCase    )

														__snake_case		:      Optional[Any]										=       self.default_image_processor
														__snake_case		:      Optional[int]										=       prepare_img()
														__snake_case		:      str										=       image_processor(images=lowerCamelCase   ,     return_tensors="pt"    ).to(lowerCamelCase    )

														# forward pass
														with torch.no_grad():
																					__snake_case		:      Tuple										=       model(**lowerCamelCase    )

														# verify the logits
														__snake_case		:      Dict										=       torch.Size((1, 1000)    )
														self.assertEqual(outputs.logits.shape   ,     lowerCamelCase    )

														__snake_case		:      Union[str, Any]										=       torch.tensor([0.92_85, 0.90_15, -0.31_50]    ).to(lowerCamelCase    )

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





from scipy.stats import spearmanr

import datasets


_snake_case					:		Optional[Any]      =    "\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n"

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

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

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




							"""simple docstring"""


							def    __snake_case (							self	:  Optional[int]    )     ->   Any:
														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    __snake_case (							self	:  Optional[Any]   ,     lowerCamelCase	:  Optional[int]   ,     lowerCamelCase	:  int   ,     lowerCamelCase	:  Tuple=False    )     ->   Dict:
														__snake_case		:      Optional[int]										=       spearmanr(lowerCamelCase   ,     lowerCamelCase    )
														if return_pvalue:
																					return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
														else:
																					return {"spearmanr": results[0]}

