


"""simple docstring"""
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 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				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 			_UpperCAmelCase :






		'''simple docstring'''

		def __init__(self				,       a_				,       a_=13				,       a_=32				,       a_=2				,       a_=3				,       a_=6_40				,       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				,       ):





			'''simple docstring'''

			__snake_case	:						int						=				parent
			__snake_case	:						int						=				batch_size
			__snake_case	:						List[Any]						=				image_size
			__snake_case	:						Optional[Any]						=				patch_size
			__snake_case	:						Any						=				num_channels
			__snake_case	:						Union[str, Any]						=				last_hidden_size
			__snake_case	:						List[str]						=				num_attention_heads
			__snake_case	:						int						=				hidden_act
			__snake_case	:						Optional[int]						=				conv_kernel_size
			__snake_case	:						int						=				output_stride
			__snake_case	:						List[str]						=				hidden_dropout_prob
			__snake_case	:						Optional[Any]						=				attention_probs_dropout_prob
			__snake_case	:						List[str]						=				classifier_dropout_prob
			__snake_case	:						Union[str, Any]						=				use_labels
			__snake_case	:						Union[str, Any]						=				is_training
			__snake_case	:						Optional[int]						=				num_labels
			__snake_case	:						int						=				initializer_range
			__snake_case	:						int						=				scope



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

			__snake_case	:						List[str]						=				self.get_config()

			return config, pixel_values, labels, pixel_labels



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''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 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				MobileViTModel(config=a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						Dict						=				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 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Optional[Any]						=				self.num_labels
			__snake_case	:						Union[str, Any]						=				MobileViTForImageClassification(a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						str						=				model(a_				,       labels=a_					)
			self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						str						=				self.num_labels
			__snake_case	:						Optional[int]						=				MobileViTForSemanticSegmentation(a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						Tuple						=				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,
			    )				,       )
			__snake_case	:						Any						=				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 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				self.prepare_config_and_inputs()
			__snake_case	,							__snake_case	,							__snake_case	,							__snake_case	:						Tuple						=				config_and_inputs
			__snake_case	:						Tuple						=				{'''pixel_values''': pixel_values}
			return config, inputs_dict



@require_torch
class 			_UpperCAmelCase (							__snake_case,				__snake_case,				unittest.TestCase				):






		'''simple docstring'''

		lowerCamelCase__				=(
		    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		lowerCamelCase__				=(
		    {
		        'feature-extraction': MobileViTModel,
		        'image-classification': MobileViTForImageClassification,
		        'image-segmentation': MobileViTForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		lowerCamelCase__				=False
		lowerCamelCase__				=False
		lowerCamelCase__				=False
		lowerCamelCase__				=False



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				MobileViTModelTester(self					)
			__snake_case	:						Any						=				MobileViTConfigTester(self				,       config_class=a_				,       has_text_modality=a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			self.config_tester.run_common_tests()



		@unittest.skip(reason='''MobileViT does not use inputs_embeds'''					)
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			pass



		@unittest.skip(reason='''MobileViT does not support input and output embeddings'''					)
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			pass



		@unittest.skip(reason='''MobileViT does not output attentions'''					)
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			pass



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__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	:						List[str]						=				model_class(a_					)
				__snake_case	:						Dict						=				inspect.signature(model.forward					)
				# signature.parameters is an OrderedDict => so arg_names order is deterministic
				__snake_case	:						Optional[Any]						=				[*signature.parameters.keys()]

				__snake_case	:						int						=				['''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 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			pass



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						List[Any]						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			def check_hidden_states_output(a_				,       a_				,       a_					):
				__snake_case	:						str						=				model_class(a_					)
				model.to(a_					)
				model.eval()

				with torch.no_grad():
					__snake_case	:						Optional[Any]						=				model(**self._prepare_for_class(a_				,       a_					)					)

				__snake_case	:						List[str]						=				outputs.hidden_states

				__snake_case	:						Tuple						=				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.
				__snake_case	:						Optional[int]						=				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					)

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

			for model_class in self.all_model_classes:
				__snake_case	:						Any						=				True
				check_hidden_states_output(a_				,       a_				,       a_					)

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

				check_hidden_states_output(a_				,       a_				,       a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_semantic_segmentation(*a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__snake_case	:						Dict						=				MobileViTModel.from_pretrained(a_					)
				self.assertIsNotNone(a_					)






def 		lowercase							(     )     ->str:
	"""simple docstring"""





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



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






		'''simple docstring'''

		@cached_property
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''					) if is_vision_available() else None



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''					).to(a_					)

			__snake_case	:						Union[str, Any]						=				self.default_image_processor
			__snake_case	:						List[str]						=				prepare_img()
			__snake_case	:						Tuple						=				image_processor(images=a_				,       return_tensors='''pt'''					).to(a_					)

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

			# verify the logits
			__snake_case	:						int						=				torch.Size((1, 10_00)					)
			self.assertEqual(outputs.logits.shape				,       a_					)

			__snake_case	:						str						=				torch.tensor([-1.9364, -1.2327, -0.4653]					).to(a_					)

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



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						int						=				MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)
			__snake_case	:						Optional[Any]						=				model.to(a_					)

			__snake_case	:						List[Any]						=				MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

			__snake_case	:						Optional[Any]						=				prepare_img()
			__snake_case	:						List[Any]						=				image_processor(images=a_				,       return_tensors='''pt'''					).to(a_					)

			# forward pass
			with torch.no_grad():
				__snake_case	:						int						=				model(**a_					)
			__snake_case	:						List[str]						=				outputs.logits

			# verify the logits
			__snake_case	:						Tuple						=				torch.Size((1, 21, 32, 32)					)
			self.assertEqual(logits.shape				,       a_					)

			__snake_case	:						int						=				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 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						List[Any]						=				MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)
			__snake_case	:						Optional[Any]						=				model.to(a_					)

			__snake_case	:						List[Any]						=				MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

			__snake_case	:						List[Any]						=				prepare_img()
			__snake_case	:						Tuple						=				image_processor(images=a_				,       return_tensors='''pt'''					).to(a_					)

			# forward pass
			with torch.no_grad():
				__snake_case	:						Union[str, Any]						=				model(**a_					)

			__snake_case	:						Union[str, Any]						=				outputs.logits.detach().cpu()

			__snake_case	:						str						=				image_processor.post_process_semantic_segmentation(outputs=a_				,       target_sizes=[(50, 60)]					)
			__snake_case	:						Any						=				torch.Size((50, 60)					)
			self.assertEqual(segmentation[0].shape				,       a_					)

			__snake_case	:						Optional[Any]						=				image_processor.post_process_semantic_segmentation(outputs=a_					)
			__snake_case	:						Dict						=				torch.Size((32, 32)					)
			self.assertEqual(segmentation[0].shape				,       a_					)








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowerCamelCase           =					{
    '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''],
    '''tokenization_canine''': ['''CanineTokenizer'''],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					[
           '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''CanineForMultipleChoice''',
           '''CanineForQuestionAnswering''',
           '''CanineForSequenceClassification''',
           '''CanineForTokenClassification''',
           '''CanineLayer''',
           '''CanineModel''',
           '''CaninePreTrainedModel''',
           '''load_tf_weights_in_canine''',
       ]


if TYPE_CHECKING:
       from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
       from .tokenization_canine import CanineTokenizer

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_canine import (
                  CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
                  CanineForMultipleChoice,
                  CanineForQuestionAnswering,
                  CanineForSequenceClassification,
                  CanineForTokenClassification,
                  CanineLayer,
                  CanineModel,
                  CaninePreTrainedModel,
                  load_tf_weights_in_canine,
              )


else:
       import sys

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