



"""simple docstring"""





import inspect
import unittest

from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
  from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor
class  lowercase__  (       SCREAMING_SNAKE_CASE ):







       '''simple docstring'''


       def 	lowercase__							(				self     :    Optional[Any]       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.config_class(**self.inputs_dict       )
             self.parent.assertTrue(hasattr(_UpperCAmelCase						,							"tf_padding"       )       )
             self.parent.assertTrue(hasattr(_UpperCAmelCase						,							"depth_multiplier"       )       )



class  lowercase__  :







       '''simple docstring'''


       def __init__(				self     :    Optional[int]						,							_UpperCAmelCase     :    Union[str, Any]						,							_UpperCAmelCase     :    str=13						,							_UpperCAmelCase     :    List[str]=3						,							_UpperCAmelCase     :    List[Any]=32						,							_UpperCAmelCase     :    Any=0.25						,							_UpperCAmelCase     :    Optional[int]=8						,							_UpperCAmelCase     :    Union[str, Any]=8						,							_UpperCAmelCase     :    Tuple=6						,							_UpperCAmelCase     :    Dict=32						,							_UpperCAmelCase     :    Dict=True						,							_UpperCAmelCase     :    Optional[Any]=True						,							_UpperCAmelCase     :    str=True						,							_UpperCAmelCase     :    int="relu6"						,							_UpperCAmelCase     :    Optional[int]=1280						,							_UpperCAmelCase     :    str=0.1						,							_UpperCAmelCase     :    List[str]=0.02						,							_UpperCAmelCase     :    Optional[int]=True						,							_UpperCAmelCase     :    str=True						,							_UpperCAmelCase     :    Optional[int]=10						,							_UpperCAmelCase     :    Optional[Any]=None						,							)					->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_     					=				parent
             UpperCAmelCase_     					=				batch_size
             UpperCAmelCase_     					=				num_channels
             UpperCAmelCase_     					=				image_size
             UpperCAmelCase_     					=				depth_multiplier
             UpperCAmelCase_     					=				depth_divisible_by
             UpperCAmelCase_     					=				min_depth
             UpperCAmelCase_     					=				expand_ratio
             UpperCAmelCase_     					=				tf_padding
             UpperCAmelCase_     					=				output_stride
             UpperCAmelCase_     					=				first_layer_is_expansion
             UpperCAmelCase_     					=				finegrained_output
             UpperCAmelCase_     					=				hidden_act
             UpperCAmelCase_     					=				last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier       )
             UpperCAmelCase_     					=				classifier_dropout_prob
             UpperCAmelCase_     					=				use_labels
             UpperCAmelCase_     					=				is_training
             UpperCAmelCase_     					=				num_labels
             UpperCAmelCase_     					=				initializer_range
             UpperCAmelCase_     					=				scope



       def 	lowercase__							(				self     :    Optional[Any]       )					->		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 	lowercase__							(				self     :    Optional[Any]       )					->		Union[str, Any]:


             '''simple docstring'''




             return MobileNetVaConfig(
                 num_channels=self.num_channels						,							image_size=self.image_size						,							depth_multiplier=self.depth_multiplier						,							depth_divisible_by=self.depth_divisible_by						,							min_depth=self.min_depth						,							expand_ratio=self.expand_ratio						,							output_stride=self.output_stride						,							first_layer_is_expansion=self.first_layer_is_expansion						,							finegrained_output=self.finegrained_output						,							hidden_act=self.hidden_act						,							tf_padding=self.tf_padding						,							classifier_dropout_prob=self.classifier_dropout_prob						,							initializer_range=self.initializer_range						,							)



       def 	lowercase__							(				self     :    int						,							_UpperCAmelCase     :    List[Any]						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    Tuple						,							_UpperCAmelCase     :    str       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaModel(config=_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				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,
                 )						,							)
             self.parent.assertEqual(
                 result.pooler_output.shape						,							(self.batch_size, self.last_hidden_size)						,							)



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.num_labels
             UpperCAmelCase_     					=				MobileNetVaForImageClassification(_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				model(_UpperCAmelCase						,							labels=_UpperCAmelCase       )
             self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.num_labels)       )



       def 	lowercase__							(				self     :    Dict						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    int						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    int       )					->		str:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.num_labels
             UpperCAmelCase_     					=				MobileNetVaForSemanticSegmentation(_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				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,
                 )						,							)
             UpperCAmelCase_     					=				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 	lowercase__							(				self     :    Dict       )					->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.prepare_config_and_inputs()
             UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_     					=				config_and_inputs
             UpperCAmelCase_     					=				{"pixel_values": pixel_values}
             return config, inputs_dict



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







       '''simple docstring'''


       UpperCamelCase		=	(
           (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       UpperCamelCase		=	(
           {
               '''feature-extraction''': MobileNetVaModel,
               '''image-classification''': MobileNetVaForImageClassification,
               '''image-segmentation''': MobileNetVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       UpperCamelCase		=	False
       UpperCamelCase		=	False
       UpperCamelCase		=	False
       UpperCamelCase		=	False



       def 	lowercase__							(				self     :    Tuple       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaModelTester(self       )
             UpperCAmelCase_     					=				MobileNetVaConfigTester(self						,							config_class=_UpperCAmelCase						,							has_text_modality=_UpperCAmelCase       )



       def 	lowercase__							(				self     :    Optional[Any]       )					->		Dict:


             '''simple docstring'''




             self.config_tester.run_common_tests()



       @unittest.skip(reason="MobileNetV2 does not use inputs_embeds"       )
       def 	lowercase__							(				self     :    Dict       )					->		List[str]:


             '''simple docstring'''




             pass



       @unittest.skip(reason="MobileNetV2 does not support input and output embeddings"       )
       def 	lowercase__							(				self     :    str       )					->		int:


             '''simple docstring'''




             pass



       @unittest.skip(reason="MobileNetV2 does not output attentions"       )
       def 	lowercase__							(				self     :    List[Any]       )					->		List[str]:


             '''simple docstring'''




             pass



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


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_     					=				model_class(_UpperCAmelCase       )
                   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]						,							_UpperCAmelCase       )



       def 	lowercase__							(				self     :    Dict       )					->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase       )



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


             '''simple docstring'''




             def check_hidden_states_output(_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    int       ):
                   UpperCAmelCase_     					=				model_class(_UpperCAmelCase       )
                   model.to(_UpperCAmelCase       )
                   model.eval()

                   with torch.no_grad():
                         UpperCAmelCase_     					=				model(**self._prepare_for_class(_UpperCAmelCase						,							_UpperCAmelCase       )       )

                   UpperCAmelCase_     					=				outputs.hidden_states

                   UpperCAmelCase_     					=				16
                   self.assertEqual(len(_UpperCAmelCase       )						,							_UpperCAmelCase       )

             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_     					=				True
                   check_hidden_states_output(_UpperCAmelCase						,							_UpperCAmelCase						,							_UpperCAmelCase       )

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

                   check_hidden_states_output(_UpperCAmelCase						,							_UpperCAmelCase						,							_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )



       def 	lowercase__							(				self     :    Optional[int]       )					->		Any:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase       )







       @slow
       def 	lowercase__							(				self     :    List[Any]       )					->		int:


             '''simple docstring'''




             for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_     					=				MobileNetVaModel.from_pretrained(_UpperCAmelCase       )
                   self.assertIsNotNone(_UpperCAmelCase       )



def   a__      ( ):
      UpperCAmelCase_     					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
      return image


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







       '''simple docstring'''


       @cached_property
       def 	lowercase__							(				self     :    Any       )					->		Dict:


             '''simple docstring'''




             return (
                 MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"       ) if is_vision_available() else None
             )



       @slow
       def 	lowercase__							(				self     :    Dict       )					->		List[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"       ).to(_UpperCAmelCase       )

             UpperCAmelCase_     					=				self.default_image_processor
             UpperCAmelCase_     					=				prepare_img()
             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="pt"       ).to(_UpperCAmelCase       )

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_     					=				model(**_UpperCAmelCase       )

             # verify the logits
             UpperCAmelCase_     					=				torch.Size((1, 1001)       )
             self.assertEqual(outputs.logits.shape						,							_UpperCAmelCase       )

             UpperCAmelCase_     					=				torch.tensor([0.2445, -1.1993, 0.1905]       ).to(_UpperCAmelCase       )

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







       @slow
       def 	lowercase__							(				self     :    List[Any]       )					->		Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"       )
             UpperCAmelCase_     					=				model.to(_UpperCAmelCase       )

             UpperCAmelCase_     					=				MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"       )

             UpperCAmelCase_     					=				prepare_img()
             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="pt"       ).to(_UpperCAmelCase       )

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_     					=				model(**_UpperCAmelCase       )
             UpperCAmelCase_     					=				outputs.logits

             # verify the logits
             UpperCAmelCase_     					=				torch.Size((1, 21, 65, 65)       )
             self.assertEqual(logits.shape						,							_UpperCAmelCase       )

             UpperCAmelCase_     					=				torch.tensor(
                 [
                     [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
                     [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
                     [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
                 ]						,							device=_UpperCAmelCase						,							)

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






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import VivitImageProcessor



class    a_ (			unittest.TestCase    ):






			def __init__(      self				,			__UpperCamelCase				,			__UpperCamelCase=7				,			__UpperCamelCase=3				,			__UpperCamelCase=10				,			__UpperCamelCase=18				,			__UpperCamelCase=30				,			__UpperCamelCase=400				,			__UpperCamelCase=True				,			__UpperCamelCase=None				,			__UpperCamelCase=True				,			__UpperCamelCase=[0.5, 0.5, 0.5]				,			__UpperCamelCase=[0.5, 0.5, 0.5]				,			__UpperCamelCase=None				,			):
									_lowercase					       =					size if size is not None else {"""shortest_edge""": 18}
									_lowercase					       =					crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

									_lowercase					       =					parent
									_lowercase					       =					batch_size
									_lowercase					       =					num_channels
									_lowercase					       =					num_frames
									_lowercase					       =					image_size
									_lowercase					       =					min_resolution
									_lowercase					       =					max_resolution
									_lowercase					       =					do_resize
									_lowercase					       =					size
									_lowercase					       =					do_normalize
									_lowercase					       =					image_mean
									_lowercase					       =					image_std
									_lowercase					       =					crop_size






			def    UpperCamelCase_				(      self  ):
									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "crop_size": self.crop_size,
									}







@require_torch
@require_vision
class    a_ (			_a					,			unittest.TestCase    ):
			a	:			str					   =							VivitImageProcessor if is_vision_available() else None






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					VivitImageProcessingTester(self  )






			@property
			def    UpperCamelCase_				(      self  ):
									return self.image_processor_tester.prepare_image_processor_dict()






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.image_processing_class(**self.image_processor_dict  )
									self.assertTrue(hasattr(__UpperCamelCase				,			"""image_mean"""  )  )
									self.assertTrue(hasattr(__UpperCamelCase				,			"""image_std"""  )  )
									self.assertTrue(hasattr(__UpperCamelCase				,			"""do_normalize"""  )  )
									self.assertTrue(hasattr(__UpperCamelCase				,			"""do_resize"""  )  )
									self.assertTrue(hasattr(__UpperCamelCase				,			"""do_center_crop"""  )  )
									self.assertTrue(hasattr(__UpperCamelCase				,			"""size"""  )  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.image_processing_class.from_dict(self.image_processor_dict  )
									self.assertEqual(image_processor.size				,			{"""shortest_edge""": 18}  )
									self.assertEqual(image_processor.crop_size				,			{"""height""": 18, """width""": 18}  )

									_lowercase					       =					self.image_processing_class.from_dict(self.image_processor_dict				,			size=42				,			crop_size=84  )
									self.assertEqual(image_processor.size				,			{"""shortest_edge""": 42}  )
									self.assertEqual(image_processor.crop_size				,			{"""height""": 84, """width""": 84}  )






			def    UpperCamelCase_				(      self  ):
									# Initialize image_processing
									_lowercase					       =					self.image_processing_class(**self.image_processor_dict  )
									# create random PIL videos
									_lowercase					       =					prepare_video_inputs(self.image_processor_tester				,			equal_resolution=__UpperCamelCase  )
									for video in video_inputs:
															self.assertIsInstance(__UpperCamelCase				,			__UpperCamelCase  )
															self.assertIsInstance(video[0]				,			Image.Image  )

									# Test not batched input
									_lowercase					       =					image_processing(video_inputs[0]				,			return_tensors="""pt"""  ).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,			(
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,			)

									# Test batched
									_lowercase					       =					image_processing(__UpperCamelCase				,			return_tensors="""pt"""  ).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,			(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,			)






			def    UpperCamelCase_				(      self  ):
									# Initialize image_processing
									_lowercase					       =					self.image_processing_class(**self.image_processor_dict  )
									# create random numpy tensors
									_lowercase					       =					prepare_video_inputs(self.image_processor_tester				,			equal_resolution=__UpperCamelCase				,			numpify=__UpperCamelCase  )
									for video in video_inputs:
															self.assertIsInstance(__UpperCamelCase				,			__UpperCamelCase  )
															self.assertIsInstance(video[0]				,			np.ndarray  )

									# Test not batched input
									_lowercase					       =					image_processing(video_inputs[0]				,			return_tensors="""pt"""  ).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,			(
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,			)

									# Test batched
									_lowercase					       =					image_processing(__UpperCamelCase				,			return_tensors="""pt"""  ).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,			(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,			)






			def    UpperCamelCase_				(      self  ):
									# Initialize image_processing
									_lowercase					       =					self.image_processing_class(**self.image_processor_dict  )
									# create random PyTorch tensors
									_lowercase					       =					prepare_video_inputs(self.image_processor_tester				,			equal_resolution=__UpperCamelCase				,			torchify=__UpperCamelCase  )
									for video in video_inputs:
															self.assertIsInstance(__UpperCamelCase				,			__UpperCamelCase  )
															self.assertIsInstance(video[0]				,			torch.Tensor  )

									# Test not batched input
									_lowercase					       =					image_processing(video_inputs[0]				,			return_tensors="""pt"""  ).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,			(
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,			)

									# Test batched
									_lowercase					       =					image_processing(__UpperCamelCase				,			return_tensors="""pt"""  ).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,			(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,			)