






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        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  self.config_class(**self.inputs_dict    )
												self.parent.assertTrue(hasattr(__A				,		'''tf_padding'''    )    )
												self.parent.assertTrue(hasattr(__A				,		'''depth_multiplier'''    )    )







class        _SCREAMING_SNAKE_CASE						:





							"""simple docstring"""





							def __init__(   self:     Optional[int]				,		__A:     Union[str, Any]				,		__A:     Any=13				,		__A:     Dict=3				,		__A:     int=32				,		__A:     Optional[Any]=0.2_5				,		__A:     List[str]=8				,		__A:     Tuple=8				,		__A:     Tuple=6				,		__A:     Optional[int]=32				,		__A:     Optional[int]=True				,		__A:     Union[str, Any]=True				,		__A:     Tuple=True				,		__A:     List[str]="relu6"				,		__A:     List[str]=1280				,		__A:     Any=0.1				,		__A:     List[str]=0.0_2				,		__A:     Union[str, Any]=True				,		__A:     Union[str, Any]=True				,		__A:     Dict=10				,		__A:     List[str]=None				,		):

												'''simple docstring'''

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




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

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

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

												a__          =  self.get_config()

												return config, pixel_values, labels, pixel_labels




							def  lowercase		(   self:     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:     Union[str, Any]				,		__A:     Union[str, Any]				,		__A:     int				,		__A:     Union[str, Any]				,		__A:     Tuple    ):

												'''simple docstring'''

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




							def  lowercase		(   self:     Union[str, Any]				,		__A:     List[str]				,		__A:     Optional[int]				,		__A:     Optional[int]				,		__A:     Any    ):

												'''simple docstring'''

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




							def  lowercase		(   self:     List[Any]				,		__A:     Union[str, Any]				,		__A:     Any				,		__A:     str				,		__A:     List[Any]    ):

												'''simple docstring'''

												a__          =  self.num_labels
												a__          =  MobileNetVaForSemanticSegmentation(__A    )
												model.to(__A    )
												model.eval()
												a__          =  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,
												    )				,		)
												a__          =  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  lowercase		(   self:     int    ):

												'''simple docstring'''

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







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





							"""simple docstring"""





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

							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  MobileNetVaModelTester(self    )
												a__          =  MobileNetVaConfigTester(self				,		config_class=__A				,		has_text_modality=__A    )




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												self.config_tester.run_common_tests()




							@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''    )
							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												pass




							@unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''    )
							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												pass




							@unittest.skip(reason='''MobileNetV2 does not output attentions'''    )
							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												pass




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()

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

																	a__          =  ['''pixel_values''']
																	self.assertListEqual(arg_names[:1]				,		__A    )




							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A    )




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												def check_hidden_states_output(__A:     Optional[Any]				,		__A:     Dict				,		__A:     Union[str, Any]    ):
																	a__          =  model_class(__A    )
																	model.to(__A    )
																	model.eval()

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

																	a__          =  outputs.hidden_states

																	a__          =  16
																	self.assertEqual(len(__A    )				,		__A    )

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()

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

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

																	check_hidden_states_output(__A				,		__A				,		__A    )




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__A    )




							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_semantic_segmentation(*__A    )





							@slow
							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

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





def        SCREAMING_SNAKE_CASE       (      ):
					a__          =  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  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

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




							@slow
							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224'''    ).to(__A    )

												a__          =  self.default_image_processor
												a__          =  prepare_img()
												a__          =  image_processor(images=__A				,		return_tensors='''pt'''    ).to(__A    )

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

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

												a__          =  torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]    ).to(__A    )

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





							@slow
							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''    )
												a__          =  model.to(__A    )

												a__          =  MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''    )

												a__          =  prepare_img()
												a__          =  image_processor(images=__A				,		return_tensors='''pt'''    ).to(__A    )

												# forward pass
												with torch.no_grad():
																	a__          =  model(**__A    )
												a__          =  outputs.logits

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

												a__          =  torch.tensor(
												    [
												        [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
												        [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
												        [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
												    ]				,		device=__A				,		)

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










"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


__a       :	Tuple             = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']}

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__a       :	Tuple             = ['DeiTFeatureExtractor']
	__a       :	Optional[Any]             = ['DeiTImageProcessor']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__a       :	Optional[int]             = [
	    'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
	    'DeiTForImageClassification',
	    'DeiTForImageClassificationWithTeacher',
	    'DeiTForMaskedImageModeling',
	    'DeiTModel',
	    'DeiTPreTrainedModel',
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__a       :	Dict             = [
	    'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
	    'TFDeiTForImageClassification',
	    'TFDeiTForImageClassificationWithTeacher',
	    'TFDeiTForMaskedImageModeling',
	    'TFDeiTModel',
	    'TFDeiTPreTrainedModel',
	]


if TYPE_CHECKING:
	from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .feature_extraction_deit import DeiTFeatureExtractor
		from .image_processing_deit import DeiTImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_deit import (
		    DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    DeiTForImageClassification,
		    DeiTForImageClassificationWithTeacher,
		    DeiTForMaskedImageModeling,
		    DeiTModel,
		    DeiTPreTrainedModel,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_deit import (
		    TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFDeiTForImageClassification,
		    TFDeiTForImageClassificationWithTeacher,
		    TFDeiTForMaskedImageModeling,
		    TFDeiTModel,
		    TFDeiTPreTrainedModel,
		)


else:
	import sys

	__a       :	List[Any]             = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


