
import inspect
import unittest

from transformers import MobileViTConfig
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_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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
					from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import MobileViTImageProcessor


class        lowercase      (	_UpperCamelCase     ):



		def __UpperCamelCase				(				self )						->      List[Any]:
				"""simple docstring"""
				UpperCamelCase						=  self.config_class(**self.inputs_dict )
				self.parent.assertTrue(hasattr(A_       ,   'hidden_sizes' ) )
				self.parent.assertTrue(hasattr(A_       ,   'neck_hidden_sizes' ) )
				self.parent.assertTrue(hasattr(A_       ,   'num_attention_heads' ) )






class        lowercase      :



		def __init__(				self       ,   A_       ,   A_=13       ,   A_=32       ,   A_=2       ,   A_=3       ,   A_=640       ,   A_=4       ,   A_="silu"       ,   A_=3       ,   A_=32       ,   A_=0.1       ,   A_=0.1       ,   A_=0.1       ,   A_=0.02       ,   A_=True       ,   A_=True       ,   A_=10       ,   A_=None       ,   )						->      Tuple:
				"""simple docstring"""
				UpperCamelCase						=  parent
				UpperCamelCase						=  batch_size
				UpperCamelCase						=  image_size
				UpperCamelCase						=  patch_size
				UpperCamelCase						=  num_channels
				UpperCamelCase						=  last_hidden_size
				UpperCamelCase						=  num_attention_heads
				UpperCamelCase						=  hidden_act
				UpperCamelCase						=  conv_kernel_size
				UpperCamelCase						=  output_stride
				UpperCamelCase						=  hidden_dropout_prob
				UpperCamelCase						=  attention_probs_dropout_prob
				UpperCamelCase						=  classifier_dropout_prob
				UpperCamelCase						=  use_labels
				UpperCamelCase						=  is_training
				UpperCamelCase						=  num_labels
				UpperCamelCase						=  initializer_range
				UpperCamelCase						=  scope



		def __UpperCamelCase				(				self )						->      Optional[int]:
				"""simple docstring"""
				UpperCamelCase						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

				UpperCamelCase						=  self.get_config()

				return config, pixel_values, labels, pixel_labels



		def __UpperCamelCase				(				self )						->      Union[str, Any]:
				"""simple docstring"""
				return MobileViTConfig(
				    image_size=self.image_size       ,   patch_size=self.patch_size       ,   num_channels=self.num_channels       ,   num_attention_heads=self.num_attention_heads       ,   hidden_act=self.hidden_act       ,   conv_kernel_size=self.conv_kernel_size       ,   output_stride=self.output_stride       ,   hidden_dropout_prob=self.hidden_dropout_prob       ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,   classifier_dropout_prob=self.classifier_dropout_prob       ,   initializer_range=self.initializer_range       ,   )



		def __UpperCamelCase				(				self       ,   A_       ,   A_       ,   A_       ,   A_ )						->      Optional[Any]:
				"""simple docstring"""
				UpperCamelCase						=  MobileViTModel(config=A_ )
				model.to(A_ )
				model.eval()
				UpperCamelCase						=  model(A_ )
				self.parent.assertEqual(
				    result.last_hidden_state.shape       ,   (
				        self.batch_size,
				        self.last_hidden_size,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )       ,   )



		def __UpperCamelCase				(				self       ,   A_       ,   A_       ,   A_       ,   A_ )						->      Optional[Any]:
				"""simple docstring"""
				UpperCamelCase						=  self.num_labels
				UpperCamelCase						=  MobileViTForImageClassification(A_ )
				model.to(A_ )
				model.eval()
				UpperCamelCase						=  model(A_       ,   labels=A_ )
				self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.num_labels) )



		def __UpperCamelCase				(				self       ,   A_       ,   A_       ,   A_       ,   A_ )						->      Optional[Any]:
				"""simple docstring"""
				UpperCamelCase						=  self.num_labels
				UpperCamelCase						=  MobileViTForSemanticSegmentation(A_ )
				model.to(A_ )
				model.eval()
				UpperCamelCase						=  model(A_ )
				self.parent.assertEqual(
				    result.logits.shape       ,   (
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )       ,   )
				UpperCamelCase						=  model(A_       ,   labels=A_ )
				self.parent.assertEqual(
				    result.logits.shape       ,   (
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )       ,   )



		def __UpperCamelCase				(				self )						->      List[Any]:
				"""simple docstring"""
				UpperCamelCase						=  self.prepare_config_and_inputs()
				UpperCamelCase						=  config_and_inputs
				UpperCamelCase						=  {"pixel_values": pixel_values}
				return config, inputs_dict






@require_torch
class        lowercase      (	_UpperCamelCase						,     _UpperCamelCase						,     unittest.TestCase     ):
		__lowercase : int			  =       (
		    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		__lowercase : Dict			  =       (
		    {
		        "feature-extraction": MobileViTModel,
		        "image-classification": MobileViTForImageClassification,
		        "image-segmentation": MobileViTForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		__lowercase : Union[str, Any]			  =       False
		__lowercase : Union[str, Any]			  =       False
		__lowercase : List[str]			  =       False
		__lowercase : List[str]			  =       False



		def __UpperCamelCase				(				self )						->      Tuple:
				"""simple docstring"""
				UpperCamelCase						=  MobileViTModelTester(self )
				UpperCamelCase						=  MobileViTConfigTester(self       ,   config_class=A_       ,   has_text_modality=A_ )



		def __UpperCamelCase				(				self )						->      Optional[int]:
				"""simple docstring"""
				self.config_tester.run_common_tests()



		@unittest.skip(reason='MobileViT does not use inputs_embeds' )
		def __UpperCamelCase				(				self )						->      Any:
				"""simple docstring"""
				pass



		@unittest.skip(reason='MobileViT does not support input and output embeddings' )
		def __UpperCamelCase				(				self )						->      Union[str, Any]:
				"""simple docstring"""
				pass



		@unittest.skip(reason='MobileViT does not output attentions' )
		def __UpperCamelCase				(				self )						->      Any:
				"""simple docstring"""
				pass



		def __UpperCamelCase				(				self )						->      List[str]:
				"""simple docstring"""
				UpperCamelCase						=  self.model_tester.prepare_config_and_inputs_for_common()

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

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



		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
		def __UpperCamelCase				(				self )						->      str:
				"""simple docstring"""
				pass



		def __UpperCamelCase				(				self )						->      Tuple:
				"""simple docstring"""
				UpperCamelCase						=  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*A_ )



		def __UpperCamelCase				(				self )						->      Optional[int]:
				"""simple docstring"""
				def check_hidden_states_output(A_       ,   A_       ,   A_ ):
						UpperCamelCase						=  model_class(A_ )
						model.to(A_ )
						model.eval()

						with torch.no_grad():
								UpperCamelCase						=  model(**self._prepare_for_class(A_       ,   A_ ) )

						UpperCamelCase						=  outputs.hidden_states

						UpperCamelCase						=  5
						self.assertEqual(len(A_ )       ,   A_ )

						# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
						# with the width and height being successively divided by 2.
						UpperCamelCase						=  2
						for i in range(len(A_ ) ):
								self.assertListEqual(
								    list(hidden_states[i].shape[-2:] )       ,   [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]       ,   )
								divisor *= 2

						self.assertEqual(self.model_tester.output_stride       ,   divisor // 2 )

				UpperCamelCase						=  self.model_tester.prepare_config_and_inputs_for_common()

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

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

						check_hidden_states_output(A_       ,   A_       ,   A_ )



		def __UpperCamelCase				(				self )						->      int:
				"""simple docstring"""
				UpperCamelCase						=  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*A_ )



		def __UpperCamelCase				(				self )						->      Optional[Any]:
				"""simple docstring"""
				UpperCamelCase						=  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*A_ )



		@slow
		def __UpperCamelCase				(				self )						->      Optional[int]:
				"""simple docstring"""
				for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						UpperCamelCase						=  MobileViTModel.from_pretrained(A_ )
						self.assertIsNotNone(A_ )






def    A (      )     ->						int:
		'''simple docstring'''

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


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



		@cached_property
		def __UpperCamelCase				(				self )						->      Union[str, Any]:
				"""simple docstring"""
				return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None



		@slow
		def __UpperCamelCase				(				self )						->      List[str]:
				"""simple docstring"""
				UpperCamelCase						=  MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(A_ )

				UpperCamelCase						=  self.default_image_processor
				UpperCamelCase						=  prepare_img()
				UpperCamelCase						=  image_processor(images=A_       ,   return_tensors='pt' ).to(A_ )

				# forward pass
				with torch.no_grad():
						UpperCamelCase						=  model(**A_ )

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

				UpperCamelCase						=  torch.tensor([-1.9364, -1.2327, -0.4653] ).to(A_ )

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



		@slow
		def __UpperCamelCase				(				self )						->      str:
				"""simple docstring"""
				UpperCamelCase						=  MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
				UpperCamelCase						=  model.to(A_ )

				UpperCamelCase						=  MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )

				UpperCamelCase						=  prepare_img()
				UpperCamelCase						=  image_processor(images=A_       ,   return_tensors='pt' ).to(A_ )

				# forward pass
				with torch.no_grad():
						UpperCamelCase						=  model(**A_ )
				UpperCamelCase						=  outputs.logits

				# verify the logits
				UpperCamelCase						=  torch.Size((1, 21, 32, 32) )
				self.assertEqual(logits.shape       ,   A_ )

				UpperCamelCase						=  torch.tensor(
				    [
				        [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
				        [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
				        [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
				    ]       ,   device=A_       ,   )

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



		@slow
		def __UpperCamelCase				(				self )						->      int:
				"""simple docstring"""
				UpperCamelCase						=  MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
				UpperCamelCase						=  model.to(A_ )

				UpperCamelCase						=  MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )

				UpperCamelCase						=  prepare_img()
				UpperCamelCase						=  image_processor(images=A_       ,   return_tensors='pt' ).to(A_ )

				# forward pass
				with torch.no_grad():
						UpperCamelCase						=  model(**A_ )

				UpperCamelCase						=  outputs.logits.detach().cpu()

				UpperCamelCase						=  image_processor.post_process_semantic_segmentation(outputs=A_       ,   target_sizes=[(50, 60)] )
				UpperCamelCase						=  torch.Size((50, 60) )
				self.assertEqual(segmentation[0].shape       ,   A_ )

				UpperCamelCase						=  image_processor.post_process_semantic_segmentation(outputs=A_ )
				UpperCamelCase						=  torch.Size((32, 32) )
				self.assertEqual(segmentation[0].shape       ,   A_ )


from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


_UpperCAmelCase      :				Any          = "\\n@inproceedings{wang2019glue,\n  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n  note={In the Proceedings of ICLR.},\n  year={2019}\n}\n"

_UpperCAmelCase      :				str          = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n"

_UpperCAmelCase      :				List[str]          = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n    \"accuracy\": Accuracy\n    \"f1\": F1 score\n    \"pearson\": Pearson Correlation\n    \"spearmanr\": Spearman Correlation\n    \"matthews_correlation\": Matthew Correlation\nExamples:\n\n    >>> glue_metric = datasets.load_metric('glue', 'sst2')  # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'mrpc')  # 'mrpc' or 'qqp'\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'stsb')\n    >>> references = [0., 1., 2., 3., 4., 5.]\n    >>> predictions = [0., 1., 2., 3., 4., 5.]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n    {'pearson': 1.0, 'spearmanr': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'cola')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def    A (      lowercase					, lowercase				)     ->						List[str]:
		'''simple docstring'''

		return float((preds == labels).mean()				)


def    A (      lowercase					, lowercase				)     ->						Tuple:
		'''simple docstring'''

		UpperCamelCase						=  simple_accuracy(lowercase					, lowercase				)
		UpperCamelCase						=  float(fa_score(y_true=lowercase					, y_pred=lowercase				)				)
		return {
		    "accuracy": acc,
		    "f1": fa,
		}


def    A (      lowercase					, lowercase				)     ->						Optional[int]:
		'''simple docstring'''

		UpperCamelCase						=  float(pearsonr(lowercase					, lowercase				)[0]				)
		UpperCamelCase						=  float(spearmanr(lowercase					, lowercase				)[0]				)
		return {
		    "pearson": pearson_corr,
		    "spearmanr": spearman_corr,
		}


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



		def __UpperCamelCase				(				self )						->      Optional[Any]:
				"""simple docstring"""
				if self.config_name not in [
				    "sst2",
				    "mnli",
				    "mnli_mismatched",
				    "mnli_matched",
				    "cola",
				    "stsb",
				    "mrpc",
				    "qqp",
				    "qnli",
				    "rte",
				    "wnli",
				    "hans",
				]:
						raise KeyError(
						    'You should supply a configuration name selected in '
						    '["sst2", "mnli", "mnli_mismatched", "mnli_matched", '
						    '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' )
				return datasets.MetricInfo(
				    description=_DESCRIPTION       ,   citation=_CITATION       ,   inputs_description=_KWARGS_DESCRIPTION       ,   features=datasets.Features(
				        {
				            'predictions': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ),
				            'references': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ),
				        } )       ,   codebase_urls=[]       ,   reference_urls=[]       ,   format='numpy'       ,   )



		def __UpperCamelCase				(				self       ,   A_       ,   A_ )						->      Any:
				"""simple docstring"""
				if self.config_name == "cola":
						return {"matthews_correlation": matthews_corrcoef(A_       ,   A_ )}
				elif self.config_name == "stsb":
						return pearson_and_spearman(A_       ,   A_ )
				elif self.config_name in ["mrpc", "qqp"]:
						return acc_and_fa(A_       ,   A_ )
				elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
						return {"accuracy": simple_accuracy(A_       ,   A_ )}
				else:
						raise KeyError(
						    'You should supply a configuration name selected in '
						    '["sst2", "mnli", "mnli_mismatched", "mnli_matched", '
						    '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' )
