'''simple docstring'''





import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
			from transformers.models.mobilevitva.modeling_mobilevitva import (
			    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
			    make_divisible,
			)


if is_vision_available():
			from PIL import Image

			from transformers import MobileViTImageProcessor




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def  snake_case__				(						self					:						str					)							->Dict:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						self.config_class(**self.inputs_dict					)
										self.parent.assertTrue(hasattr(lowercase__       ,		"width_multiplier"					)					)





class 		SCREAMING_SNAKE_CASE     :







				'''simple docstring'''





				def __init__(						self					:						List[Any]       ,		lowercase__					:						Optional[Any]       ,		lowercase__					:						Optional[Any]=13       ,		lowercase__					:						List[Any]=64       ,		lowercase__					:						List[str]=2       ,		lowercase__					:						Tuple=3       ,		lowercase__					:						Optional[Any]="swish"       ,		lowercase__					:						int=3       ,		lowercase__					:						List[str]=32       ,		lowercase__					:						Tuple=0.1       ,		lowercase__					:						str=0.0_2       ,		lowercase__					:						Any=True       ,		lowercase__					:						List[Any]=True       ,		lowercase__					:						List[str]=10       ,		lowercase__					:						str=None       ,		lowercase__					:						Optional[Any]=0.2_5       ,		lowercase__					:						List[str]=0.0       ,		lowercase__					:						List[Any]=0.0       ,		)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						parent
										_UpperCamelCase			:			Union[str, Any]   			=						batch_size
										_UpperCamelCase			:			Dict   			=						image_size
										_UpperCamelCase			:			str   			=						patch_size
										_UpperCamelCase			:			List[Any]   			=						num_channels
										_UpperCamelCase			:			List[str]   			=						make_divisible(512 * width_multiplier       ,		divisor=8					)
										_UpperCamelCase			:			Optional[Any]   			=						hidden_act
										_UpperCamelCase			:			List[str]   			=						conv_kernel_size
										_UpperCamelCase			:			Union[str, Any]   			=						output_stride
										_UpperCamelCase			:			Optional[Any]   			=						classifier_dropout_prob
										_UpperCamelCase			:			int   			=						use_labels
										_UpperCamelCase			:			Optional[Any]   			=						is_training
										_UpperCamelCase			:			Optional[Any]   			=						num_labels
										_UpperCamelCase			:			Tuple   			=						initializer_range
										_UpperCamelCase			:			Tuple   			=						scope
										_UpperCamelCase			:			Tuple   			=						width_multiplier
										_UpperCamelCase			:			Optional[Any]   			=						ffn_dropout
										_UpperCamelCase			:			int   			=						attn_dropout





				def  snake_case__				(						self					:						List[Any]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

										_UpperCamelCase			:			Dict   			=						None
										_UpperCamelCase			:			Optional[Any]   			=						None
										if self.use_labels:
																_UpperCamelCase			:			str   			=						ids_tensor([self.batch_size]       ,		self.num_labels					)
																_UpperCamelCase			:			str   			=						ids_tensor([self.batch_size, self.image_size, self.image_size]       ,		self.num_labels					)

										_UpperCamelCase			:			int   			=						self.get_config()

										return config, pixel_values, labels, pixel_labels





				def  snake_case__				(						self					:						int					)							->Any:


										'''simple docstring'''




										return MobileViTVaConfig(
										    image_size=self.image_size       ,		patch_size=self.patch_size       ,		num_channels=self.num_channels       ,		hidden_act=self.hidden_act       ,		conv_kernel_size=self.conv_kernel_size       ,		output_stride=self.output_stride       ,		classifier_dropout_prob=self.classifier_dropout_prob       ,		initializer_range=self.initializer_range       ,		width_multiplier=self.width_multiplier       ,		ffn_dropout=self.ffn_dropout_prob       ,		attn_dropout=self.attn_dropout_prob       ,		)





				def  snake_case__				(						self					:						Union[str, Any]       ,		lowercase__					:						List[Any]       ,		lowercase__					:						int       ,		lowercase__					:						Any       ,		lowercase__					:						Optional[int]					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						MobileViTVaModel(config=lowercase__					)
										model.to(lowercase__					)
										model.eval()
										_UpperCamelCase			:			List[str]   			=						model(lowercase__					)
										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  snake_case__				(						self					:						Optional[int]       ,		lowercase__					:						Tuple       ,		lowercase__					:						List[Any]       ,		lowercase__					:						Dict       ,		lowercase__					:						Union[str, Any]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						self.num_labels
										_UpperCamelCase			:			Optional[int]   			=						MobileViTVaForImageClassification(lowercase__					)
										model.to(lowercase__					)
										model.eval()
										_UpperCamelCase			:			Optional[int]   			=						model(lowercase__       ,		labels=lowercase__					)
										self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.num_labels)					)





				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]       ,		lowercase__					:						str       ,		lowercase__					:						Dict					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						self.num_labels
										_UpperCamelCase			:			Tuple   			=						MobileViTVaForSemanticSegmentation(lowercase__					)
										model.to(lowercase__					)
										model.eval()
										_UpperCamelCase			:			List[str]   			=						model(lowercase__					)
										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			:			Dict   			=						model(lowercase__       ,		labels=lowercase__					)
										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  snake_case__				(						self					:						str					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						self.prepare_config_and_inputs()
										_UpperCamelCase			,       _UpperCamelCase			,       _UpperCamelCase			,       _UpperCamelCase			:			int   			=						config_and_inputs
										_UpperCamelCase			:			Union[str, Any]   			=						{"pixel_values": pixel_values}
										return config, inputs_dict





@require_torch
class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , unittest.TestCase	):







				'''simple docstring'''
				UpperCAmelCase__							=							(
				    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)

				UpperCAmelCase__							=							(
				    {
				        '''feature-extraction''': MobileViTVaModel,
				        '''image-classification''': MobileViTVaForImageClassification,
				        '''image-segmentation''': MobileViTVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				UpperCAmelCase__							=							False
				UpperCAmelCase__							=							False
				UpperCAmelCase__							=							False
				UpperCAmelCase__							=							False





				def  snake_case__				(						self					:						Union[str, Any]					)							->str:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						MobileViTVaModelTester(self					)
										_UpperCamelCase			:			Optional[Any]   			=						MobileViTVaConfigTester(self       ,		config_class=lowercase__       ,		has_text_modality=lowercase__					)





				def  snake_case__				(						self					:						Tuple					)							->Any:


										'''simple docstring'''




										self.config_tester.run_common_tests()





				@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"					)
				def  snake_case__				(						self					:						str					)							->Tuple:


										'''simple docstring'''




										pass





				@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"					)
				def  snake_case__				(						self					:						Any					)							->Optional[int]:


										'''simple docstring'''




										pass





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


										'''simple docstring'''




										pass





				@require_torch_multi_gpu
				@unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."					)
				def  snake_case__				(						self					:						str					)							->Dict:


										'''simple docstring'''




										pass





				@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."					)
				def  snake_case__				(						self					:						int					)							->Dict:


										'''simple docstring'''




										pass





				def  snake_case__				(						self					:						str					)							->Dict:


										'''simple docstring'''




										_UpperCamelCase			,       _UpperCamelCase			:			Any   			=						self.model_tester.prepare_config_and_inputs_for_common()

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

																_UpperCamelCase			:			Optional[Any]   			=						["pixel_values"]
																self.assertListEqual(arg_names[:1]       ,		lowercase__					)





				def  snake_case__				(						self					:						List[Any]					)							->str:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowercase__					)





				def  snake_case__				(						self					:						Dict					)							->Tuple:


										'''simple docstring'''




										def check_hidden_states_output(lowercase__					:						Optional[int]       ,		lowercase__					:						List[str]       ,		lowercase__					:						int					):
																_UpperCamelCase			:			Optional[int]   			=						model_class(lowercase__					)
																model.to(lowercase__					)
																model.eval()

																with torch.no_grad():
																						_UpperCamelCase			:			List[Any]   			=						model(**self._prepare_for_class(lowercase__       ,		lowercase__					)					)

																_UpperCamelCase			:			Dict   			=						outputs.hidden_states

																_UpperCamelCase			:			str   			=						5
																self.assertEqual(len(lowercase__					)       ,		lowercase__					)

																# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
																# with the width and height being successively divided by 2.
																_UpperCamelCase			:			Any   			=						2
																for i in range(len(lowercase__					)					):
																						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			,       _UpperCamelCase			:			Optional[Any]   			=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

																check_hidden_states_output(lowercase__       ,		lowercase__       ,		lowercase__					)





				def  snake_case__				(						self					:						str					)							->List[Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowercase__					)





				def  snake_case__				(						self					:						str					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*lowercase__					)







				@slow
				def  snake_case__				(						self					:						str					)							->Tuple:


										'''simple docstring'''




										for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase			:			str   			=						MobileViTVaModel.from_pretrained(lowercase__					)
																self.assertIsNotNone(lowercase__					)





def 						__A							(     )     ->			Union[str, Any]:




						'''simple docstring'''
						_UpperCamelCase			:			Dict   			=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
						return image






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







				'''simple docstring'''





				@cached_property
				def  snake_case__				(						self					:						Optional[int]					)							->Tuple:


										'''simple docstring'''




										return (
										    MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					)
										    if is_vision_available()
										    else None
										)





				@slow
				def  snake_case__				(						self					:						Tuple					)							->List[str]:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					).to(
										    lowercase__					)

										_UpperCamelCase			:			int   			=						self.default_image_processor
										_UpperCamelCase			:			List[str]   			=						prepare_img()
										_UpperCamelCase			:			Dict   			=						image_processor(images=lowercase__       ,		return_tensors="pt"					).to(lowercase__					)

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

										# verify the logits
										_UpperCamelCase			:			str   			=						torch.Size((1, 1_000)					)
										self.assertEqual(outputs.logits.shape       ,		lowercase__					)

										_UpperCamelCase			:			Optional[Any]   			=						torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]					).to(lowercase__					)

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





				@slow
				def  snake_case__				(						self					:						int					)							->Dict:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
										_UpperCamelCase			:			Any   			=						model.to(lowercase__					)

										_UpperCamelCase			:			List[str]   			=						MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

										_UpperCamelCase			:			Optional[Any]   			=						prepare_img()
										_UpperCamelCase			:			Dict   			=						image_processor(images=lowercase__       ,		return_tensors="pt"					).to(lowercase__					)

										# forward pass
										with torch.no_grad():
																_UpperCamelCase			:			Tuple   			=						model(**lowercase__					)
										_UpperCamelCase			:			Union[str, Any]   			=						outputs.logits

										# verify the logits
										_UpperCamelCase			:			str   			=						torch.Size((1, 21, 32, 32)					)
										self.assertEqual(logits.shape       ,		lowercase__					)

										_UpperCamelCase			:			List[str]   			=						torch.tensor(
										    [
										        [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
										        [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
										        [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
										    ]       ,		device=lowercase__       ,		)

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







				@slow
				def  snake_case__				(						self					:						Union[str, Any]					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			List[str]   			=						MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
										_UpperCamelCase			:			Any   			=						model.to(lowercase__					)

										_UpperCamelCase			:			List[str]   			=						MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

										_UpperCamelCase			:			int   			=						prepare_img()
										_UpperCamelCase			:			List[str]   			=						image_processor(images=lowercase__       ,		return_tensors="pt"					).to(lowercase__					)

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

										_UpperCamelCase			:			Any   			=						outputs.logits.detach().cpu()

										_UpperCamelCase			:			int   			=						image_processor.post_process_semantic_segmentation(outputs=lowercase__       ,		target_sizes=[(50, 60)]					)
										_UpperCamelCase			:			List[str]   			=						torch.Size((50, 60)					)
										self.assertEqual(segmentation[0].shape       ,		lowercase__					)

										_UpperCamelCase			:			Union[str, Any]   			=						image_processor.post_process_semantic_segmentation(outputs=lowercase__					)
										_UpperCamelCase			:			Optional[int]   			=						torch.Size((32, 32)					)
										self.assertEqual(segmentation[0].shape       ,		lowercase__					)



'''simple docstring'''





import re
from pathlib import Path
from unittest import TestCase

import pytest




@pytest.mark.integration
class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def  snake_case__				(						self					:						Dict       ,		lowercase__					:						str					)							->Tuple:


										'''simple docstring'''




										with open(lowercase__       ,		encoding="utf-8"					) as input_file:
																_UpperCamelCase			:			Optional[int]   			=						re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)"					)
																_UpperCamelCase			:			Dict   			=						input_file.read()
																_UpperCamelCase			:			Dict   			=						regexp.search(lowercase__					)

										return match





				def  snake_case__				(						self					:						str       ,		lowercase__					:						str					)							->Tuple:


										'''simple docstring'''




										with open(lowercase__       ,		encoding="utf-8"					) as input_file:
																_UpperCamelCase			:			str   			=						re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()"       ,		re.DOTALL					)
																_UpperCamelCase			:			Optional[Any]   			=						input_file.read()
																# use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
																_UpperCamelCase			:			List[str]   			=						regexp.finditer(lowercase__					)

										_UpperCamelCase			:			Any   			=						[match for match in matches if match is not None and match.group(1					) is not None]
										return matches[0] if matches else None





				def  snake_case__				(						self					:						Optional[int]					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						Path("./datasets"					)
										_UpperCamelCase			:			List[Any]   			=						list(dataset_paths.absolute().glob("**/*.py"					)					)

										for dataset in dataset_files:
																if self._no_encoding_on_file_open(str(lowercase__					)					):
																						raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}'''					)







				def  snake_case__				(						self					:						Optional[Any]					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						Path("./datasets"					)
										_UpperCamelCase			:			Any   			=						list(dataset_paths.absolute().glob("**/*.py"					)					)

										for dataset in dataset_files:
																if self._no_print_statements(str(lowercase__					)					):
																						raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.'''					)


