

import inspect
import unittest

from huggingface_hub import hf_hub_download

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

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


if is_torch_available():
			import torch

			from transformers import UperNetForSemanticSegmentation
			from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor

class 							UpperCAmelCase_						:
							"""simple docstring"""







							def __init__(     self			,				_a			,				_a=1_3			,				_a=3_2			,				_a=3			,				_a=4			,				_a=[1_0, 2_0, 3_0, 4_0]			,				_a=[2, 2, 3, 2]			,				_a=True			,				_a=True			,				_a=3_7			,				_a="gelu"			,				_a=1_0			,				_a=0.02			,				_a=["stage2", "stage3", "stage4"]			,				_a=3			,				_a=None			,				)       ->       Any:
												_a      :       Dict   =						parent
												_a      :       List[str]   =						batch_size
												_a      :       Any   =						image_size
												_a      :       Optional[int]   =						num_channels
												_a      :       List[Any]   =						num_stages
												_a      :       List[str]   =						hidden_sizes
												_a      :       Tuple   =						depths
												_a      :       Any   =						is_training
												_a      :       Optional[int]   =						use_labels
												_a      :       Optional[Any]   =						intermediate_size
												_a      :       Optional[int]   =						hidden_act
												_a      :       Dict   =						type_sequence_label_size
												_a      :       str   =						initializer_range
												_a      :       Optional[int]   =						out_features
												_a      :       List[str]   =						num_labels
												_a      :       Optional[Any]   =						scope
												_a      :       Optional[int]   =						num_stages


							def 							__lowercase							(     self			)       ->       List[Any]:
												_a      :       Any   =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

												_a      :       Tuple   =						None
												if self.use_labels:
																	_a      :       Optional[int]   =						ids_tensor([self.batch_size]			,				self.type_sequence_label_size			)

												_a      :       Any   =						self.get_config()

												return config, pixel_values, labels


							def 							__lowercase							(     self			)       ->       Dict:
												return ConvNextConfig(
												    num_channels=self.num_channels			,				num_stages=self.num_stages			,				hidden_sizes=self.hidden_sizes			,				depths=self.depths			,				is_training=self.is_training			,				intermediate_size=self.intermediate_size			,				hidden_act=self.hidden_act			,				out_features=self.out_features			,				)


							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												return UperNetConfig(
												    backbone_config=self.get_backbone_config()			,				hidden_size=5_1_2			,				pool_scales=[1, 2, 3, 6]			,				use_auxiliary_head=_a			,				auxiliary_loss_weight=0.4			,				auxiliary_in_channels=4_0			,				auxiliary_channels=2_5_6			,				auxiliary_num_convs=1			,				auxiliary_concat_input=_a			,				loss_ignore_index=2_5_5			,				num_labels=self.num_labels			,				)


							def 							__lowercase							(     self			,				_a			,				_a			,				_a			)       ->       Any:
												_a      :       Dict   =						UperNetForSemanticSegmentation(config=_a			)
												model.to(_a			)
												model.eval()
												_a      :       List[str]   =						model(_a			)
												self.parent.assertEqual(
												    result.logits.shape			,				(self.batch_size, self.num_labels, self.image_size, self.image_size)			)




							def 							__lowercase							(     self			)       ->       Optional[Any]:
												_a      :       Tuple   =						self.prepare_config_and_inputs()
												(
												    (
												    _a
												) ,   (
												    _a
												) ,   (
												    _a
												) ,   
												)      :       Dict   =						config_and_inputs
												_a      :       Union[str, Any]   =						{'''pixel_values''': pixel_values}
												return config, inputs_dict



@require_torch
class 							UpperCAmelCase_						(     __lowercase							,			__lowercase							,			unittest.TestCase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		Tuple             =       (UperNetForSemanticSegmentation,) if is_torch_available() else ()
							UpperCAmelCase__			:		Union[str, Any]             =       {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
							UpperCAmelCase__			:		Tuple             =       False
							UpperCAmelCase__			:		int             =       False
							UpperCAmelCase__			:		List[Any]             =       False
							UpperCAmelCase__			:		List[Any]             =       False
							UpperCAmelCase__			:		Tuple             =       False
							UpperCAmelCase__			:		Tuple             =       False


							def 							__lowercase							(     self			)       ->       str:
												_a      :       Dict   =						UperNetModelTester(self			)
												_a      :       Tuple   =						ConfigTester(self			,				config_class=_a			,				has_text_modality=_a			,				hidden_size=3_7			)


							def 							__lowercase							(     self			)       ->       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 							__lowercase							(     self			)       ->       Optional[int]:
												return


							def 							__lowercase							(     self			)       ->       Tuple:
												_a ,   _a      :       int   =						self.model_tester.prepare_config_and_inputs_for_common()

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

																	_a      :       Any   =						['''pixel_values''']
																	self.assertListEqual(arg_names[:1]			,				_a			)


							def 							__lowercase							(     self			)       ->       Tuple:
												_a      :       Dict   =						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_semantic_segmentation(*_a			)


							@unittest.skip(reason='''UperNet does not use inputs_embeds'''			)
							def 							__lowercase							(     self			)       ->       Optional[int]:
												pass


							@unittest.skip(reason='''UperNet does not support input and output embeddings'''			)
							def 							__lowercase							(     self			)       ->       Dict:
												pass


							@unittest.skip(reason='''UperNet does not have a base model'''			)
							def 							__lowercase							(     self			)       ->       Dict:
												pass


							@unittest.skip(reason='''UperNet does not have a base model'''			)
							def 							__lowercase							(     self			)       ->       int:
												pass


							@require_torch_multi_gpu
							@unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''			)
							def 							__lowercase							(     self			)       ->       Any:
												pass


							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
							def 							__lowercase							(     self			)       ->       List[str]:
												pass


							def 							__lowercase							(     self			)       ->       int:
												def check_hidden_states_output(_a			,				_a			,				_a			):
																	_a      :       Union[str, Any]   =						model_class(_a			)
																	model.to(_a			)
																	model.eval()

																	with torch.no_grad():
																						_a      :       Any   =						model(**self._prepare_for_class(_a			,				_a			)			)

																	_a      :       Optional[Any]   =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	_a      :       Optional[int]   =						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]			,				)

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

												for model_class in self.all_model_classes:
																	_a      :       int   =						True
																	check_hidden_states_output(_a			,				_a			,				_a			)

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

																	check_hidden_states_output(_a			,				_a			,				_a			)


							def 							__lowercase							(     self			)       ->       int:
												_a ,   _a      :       int   =						self.model_tester.prepare_config_and_inputs_for_common()

												_a      :       List[str]   =						_config_zero_init(_a			)
												_a      :       Tuple   =						_config_zero_init(configs_no_init.backbone_config			)
												for model_class in self.all_model_classes:
																	_a      :       Dict   =						model_class(config=_a			)
																	for name, param in model.named_parameters():
																						if param.requires_grad:
																											self.assertIn(
																											    ((param.data.mean() * 1e9).round() / 1e9).item()			,				[0.0, 1.0]			,				msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""			,				)


							@unittest.skip(reason='''UperNet does not have tied weights'''			)
							def 							__lowercase							(     self			)       ->       List[Any]:
												pass




							@slow
							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_a      :       Tuple   =						UperNetForSemanticSegmentation.from_pretrained(_a			)
																	self.assertIsNotNone(_a			)



def   __UpperCAmelCase					(      )     ->	Dict:

					"""simple docstring"""

					_a      :       str   =						hf_hub_download(
					    repo_id='''hf-internal-testing/fixtures_ade20k'''						,repo_type='''dataset'''						,filename='''ADE_val_00000001.jpg'''      )
					_a      :       Optional[int]   =						Image.open(__a      ).convert('''RGB'''      )
					return image







@require_torch
@require_vision
@slow
class 							UpperCAmelCase_						(     unittest.TestCase  ):
							"""simple docstring"""







							def 							__lowercase							(     self			)       ->       int:
												_a      :       List[str]   =						AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''			)
												_a      :       List[str]   =						UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''			).to(_a			)

												_a      :       List[str]   =						prepare_img()
												_a      :       Union[str, Any]   =						processor(images=_a			,				return_tensors='''pt'''			).to(_a			)

												with torch.no_grad():
																	_a      :       Union[str, Any]   =						model(**_a			)

												_a      :       str   =						torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)			)
												self.assertEqual(outputs.logits.shape			,				_a			)

												_a      :       Tuple   =						torch.tensor(
												    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]			).to(_a			)
												self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]			,				_a			,				atol=1e-4			)			)




							def 							__lowercase							(     self			)       ->       str:
												_a      :       Tuple   =						AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''			)
												_a      :       Union[str, Any]   =						UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''			).to(_a			)

												_a      :       Dict   =						prepare_img()
												_a      :       Union[str, Any]   =						processor(images=_a			,				return_tensors='''pt'''			).to(_a			)

												with torch.no_grad():
																	_a      :       Dict   =						model(**_a			)

												_a      :       int   =						torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)			)
												self.assertEqual(outputs.logits.shape			,				_a			)

												_a      :       Any   =						torch.tensor(
												    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]			).to(_a			)
												self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]			,				_a			,				atol=1e-4			)			)






from scipy.stats import spearmanr

import datasets


a__												=						'''
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.
'''

a__												=						'''
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
'''

a__												=						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 							UpperCAmelCase_						(     datasets.Metric  ):
							"""simple docstring"""







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



