



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 				_a						(       SCREAMING_SNAKE_CASE			):





							'''simple docstring'''

							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Optional[int]      						= self.config_class(**self.inputs_dict				)
											self.parent.assertTrue(hasattr(__UpperCAmelCase ,					"width_multiplier"				)				)





class 				_a						:





							'''simple docstring'''

							def __init__(							self ,					__UpperCAmelCase ,					__UpperCAmelCase=13 ,					__UpperCAmelCase=64 ,					__UpperCAmelCase=2 ,					__UpperCAmelCase=3 ,					__UpperCAmelCase="swish" ,					__UpperCAmelCase=3 ,					__UpperCAmelCase=32 ,					__UpperCAmelCase=0.1 ,					__UpperCAmelCase=0.0_2 ,					__UpperCAmelCase=True ,					__UpperCAmelCase=True ,					__UpperCAmelCase=10 ,					__UpperCAmelCase=None ,					__UpperCAmelCase=0.2_5 ,					__UpperCAmelCase=0.0 ,					__UpperCAmelCase=0.0 ,					):







											"""simple docstring"""



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



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							int      						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

											a__	:							Dict      						= self.get_config()

											return config, pixel_values, labels, pixel_labels



							def 		_A	(							self				):







											"""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 		_A	(							self ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				):







											"""simple docstring"""



											a__	:							str      						= MobileViTVaModel(config=__UpperCAmelCase				)
											model.to(__UpperCAmelCase				)
											model.eval()
											a__	:							List[str]      						= model(__UpperCAmelCase				)
											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 		_A	(							self ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				):







											"""simple docstring"""



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



							def 		_A	(							self ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				):







											"""simple docstring"""



											a__	:							Any      						= self.num_labels
											a__	:							Any      						= MobileViTVaForSemanticSegmentation(__UpperCAmelCase				)
											model.to(__UpperCAmelCase				)
											model.eval()
											a__	:							List[str]      						= model(__UpperCAmelCase				)
											self.parent.assertEqual(
											    result.logits.shape ,					(
											        self.batch_size,
											        self.num_labels,
											        self.image_size // self.output_stride,
											        self.image_size // self.output_stride,
											    ) ,					)
											a__	:							Union[str, Any]      						= model(__UpperCAmelCase ,					labels=__UpperCAmelCase				)
											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 		_A	(							self				):







											"""simple docstring"""



											a__	:							Any      						= self.prepare_config_and_inputs()
											a__						,   a__						,   a__						,   a__	:							List[Any]      						= config_and_inputs
											a__	:							Optional[Any]      						= {"pixel_values": pixel_values}
											return config, inputs_dict





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





							'''simple docstring'''

							A				:str =       (
							    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)

							A				:List[str] =       (
							    {
							        "feature-extraction": MobileViTVaModel,
							        "image-classification": MobileViTVaForImageClassification,
							        "image-segmentation": MobileViTVaForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							A				:Any =       False
							A				:Tuple =       False
							A				:List[Any] =       False
							A				:int =       False



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Dict      						= MobileViTVaModelTester(self				)
											a__	:							Tuple      						= MobileViTVaConfigTester(self ,					config_class=__UpperCAmelCase ,					has_text_modality=__UpperCAmelCase				)



							def 		_A	(							self				):







											"""simple docstring"""



											self.config_tester.run_common_tests()



							@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"				)
							def 		_A	(							self				):







											"""simple docstring"""



											pass



							@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"				)
							def 		_A	(							self				):







											"""simple docstring"""



											pass



							@unittest.skip(reason="MobileViTV2 does not output attentions"				)
							def 		_A	(							self				):







											"""simple docstring"""



											pass



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







											"""simple docstring"""



											pass



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







											"""simple docstring"""



											pass



							def 		_A	(							self				):







											"""simple docstring"""



											a__						,   a__	:							Optional[int]      						= self.model_tester.prepare_config_and_inputs_for_common()

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

															a__	:							Dict      						= ["pixel_values"]
															self.assertListEqual(arg_names[:1] ,					__UpperCAmelCase				)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							str      						= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__UpperCAmelCase				)



							def 		_A	(							self				):







											"""simple docstring"""



											def check_hidden_states_output(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				):
															a__	:							Tuple      						= model_class(__UpperCAmelCase				)
															model.to(__UpperCAmelCase				)
															model.eval()

															with torch.no_grad():
																			a__	:							int      						= model(**self._prepare_for_class(__UpperCAmelCase ,					__UpperCAmelCase				)				)

															a__	:							Union[str, Any]      						= outputs.hidden_states

															a__	:							Dict      						= 5
															self.assertEqual(len(__UpperCAmelCase				) ,					__UpperCAmelCase				)

															# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
															# with the width and height being successively divided by 2.
															a__	:							str      						= 2
															for i in range(len(__UpperCAmelCase				)				):
																			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				)

											a__						,   a__	:							Union[str, Any]      						= self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															a__	:							Dict      						= True
															check_hidden_states_output(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				)

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

															check_hidden_states_output(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Dict      						= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase				)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Union[str, Any]      						= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase				)




							@slow
							def 		_A	(							self				):







											"""simple docstring"""



											for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															a__	:							Dict      						= MobileViTVaModel.from_pretrained(__UpperCAmelCase				)
															self.assertIsNotNone(__UpperCAmelCase				)






def     SCREAMING_SNAKE_CASE(      )	->						Any:
				a__	:							Union[str, Any]      						= Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
				return image






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





							'''simple docstring'''

							@cached_property
							def 		_A	(							self				):







											"""simple docstring"""



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



							@slow
							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							List[str]      						= MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"				).to(
											    __UpperCAmelCase				)

											a__	:							Union[str, Any]      						= self.default_image_processor
											a__	:							Any      						= prepare_img()
											a__	:							Union[str, Any]      						= image_processor(images=__UpperCAmelCase ,					return_tensors="pt"				).to(__UpperCAmelCase				)

											# forward pass
											with torch.no_grad():
															a__	:							str      						= model(**__UpperCAmelCase				)

											# verify the logits
											a__	:							Any      						= torch.Size((1, 1000)				)
											self.assertEqual(outputs.logits.shape ,					__UpperCAmelCase				)

											a__	:							Dict      						= torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01]				).to(__UpperCAmelCase				)

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



							@slow
							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							int      						= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"				)
											a__	:							str      						= model.to(__UpperCAmelCase				)

											a__	:							Optional[Any]      						= MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"				)

											a__	:							Optional[Any]      						= prepare_img()
											a__	:							int      						= image_processor(images=__UpperCAmelCase ,					return_tensors="pt"				).to(__UpperCAmelCase				)

											# forward pass
											with torch.no_grad():
															a__	:							Union[str, Any]      						= model(**__UpperCAmelCase				)
											a__	:							Optional[Any]      						= outputs.logits

											# verify the logits
											a__	:							Optional[int]      						= torch.Size((1, 21, 32, 32)				)
											self.assertEqual(logits.shape ,					__UpperCAmelCase				)

											a__	:							Dict      						= 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=__UpperCAmelCase ,					)

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




							@slow
							def 		_A	(							self				):







											"""simple docstring"""



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

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

											a__	:							str      						= prepare_img()
											a__	:							str      						= image_processor(images=__UpperCAmelCase ,					return_tensors="pt"				).to(__UpperCAmelCase				)

											# forward pass
											with torch.no_grad():
															a__	:							str      						= model(**__UpperCAmelCase				)

											a__	:							Dict      						= outputs.logits.detach().cpu()

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

											a__	:							int      						= image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase				)
											a__	:							Any      						= torch.Size((32, 32)				)
											self.assertEqual(segmentation[0].shape ,					__UpperCAmelCase				)







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


lowerCamelCase		       =      {
    """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""],
    """processing_trocr""": ["""TrOCRProcessor"""],
}


try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowerCamelCase		       =      [
						    """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""",
						    """TrOCRForCausalLM""",
						    """TrOCRPreTrainedModel""",
						]


if TYPE_CHECKING:
						from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
						from .processing_trocr import TrOCRProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
						import sys

						lowerCamelCase		       =      _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


