


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, MobileNetVaModel
	from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import MobileNetVaImageProcessor



class 				A       (			UpperCAmelCase__				):
					'''simple docstring'''






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




							"""simple docstring"""


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






class 				A       :
					'''simple docstring'''






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




							"""simple docstring"""


							lowercase__	     =						parent
							lowercase__	     =						batch_size
							lowercase__	     =						num_channels
							lowercase__	     =						image_size
							lowercase__	     =						depth_multiplier
							lowercase__	     =						min_depth
							lowercase__	     =						tf_padding
							lowercase__	     =						int(last_hidden_size * depth_multiplier						)
							lowercase__	     =						output_stride
							lowercase__	     =						hidden_act
							lowercase__	     =						classifier_dropout_prob
							lowercase__	     =						use_labels
							lowercase__	     =						is_training
							lowercase__	     =						num_labels
							lowercase__	     =						initializer_range
							lowercase__	     =						scope

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




							"""simple docstring"""


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

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

							lowercase__	     =						self.get_config()

							return config, pixel_values, labels, pixel_labels

					def     lowerCamelCase__	(self       :		str						)		->  int:




							"""simple docstring"""


							return MobileNetVaConfig(
							    num_channels=self.num_channels ,   image_size=self.image_size ,   depth_multiplier=self.depth_multiplier ,   min_depth=self.min_depth ,   tf_padding=self.tf_padding ,   hidden_act=self.hidden_act ,   classifier_dropout_prob=self.classifier_dropout_prob ,   initializer_range=self.initializer_range ,   )

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




							"""simple docstring"""


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




							"""simple docstring"""


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


					def     lowerCamelCase__	(self       :		List[Any]						)		->  Dict:




							"""simple docstring"""


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






@require_torch
class 				A       (			UpperCAmelCase__					,    UpperCAmelCase__					,    unittest.TestCase				):
					'''simple docstring'''






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

					A__     =					False
					A__     =					False
					A__     =					False
					A__     =					False

					def     lowerCamelCase__	(self       :		List[str]						)		->  List[str]:




							"""simple docstring"""


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

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




							"""simple docstring"""


							self.config_tester.run_common_tests()

					@unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""						)
					def     lowerCamelCase__	(self       :		List[Any]						)		->  Optional[Any]:




							"""simple docstring"""


							pass

					@unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""						)
					def     lowerCamelCase__	(self       :		Union[str, Any]						)		->  Tuple:




							"""simple docstring"""


							pass

					@unittest.skip(reason="""MobileNetV1 does not output attentions"""						)
					def     lowerCamelCase__	(self       :		Any						)		->  int:




							"""simple docstring"""


							pass

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




							"""simple docstring"""


							lowercase__     ,      lowercase__	     =						self.model_tester.prepare_config_and_inputs_for_common()

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

									lowercase__	     =						["""pixel_values"""]
									self.assertListEqual(arg_names[:1] ,   _UpperCAmelCase						)

					def     lowerCamelCase__	(self       :		Tuple						)		->  List[str]:




							"""simple docstring"""


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

					def     lowerCamelCase__	(self       :		List[Any]						)		->  Any:




							"""simple docstring"""


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

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

									lowercase__	     =						outputs.hidden_states

									lowercase__	     =						26
									self.assertEqual(len(_UpperCAmelCase						) ,   _UpperCAmelCase						)

							lowercase__     ,      lowercase__	     =						self.model_tester.prepare_config_and_inputs_for_common()

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

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

									check_hidden_states_output(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase						)

					def     lowerCamelCase__	(self       :		Tuple						)		->  str:




							"""simple docstring"""


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


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




							"""simple docstring"""


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






def 					UpperCamelCase   (      )  ->    Any:
		"""simple docstring"""




		lowercase__	     =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
		return image







@require_torch
@require_vision
class 				A       (			unittest.TestCase				):
					'''simple docstring'''






					@cached_property
					def     lowerCamelCase__	(self       :		Tuple						)		->  Any:




							"""simple docstring"""


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


					@slow
					def     lowerCamelCase__	(self       :		List[str]						)		->  Dict:




							"""simple docstring"""


							lowercase__	     =						MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""						).to(_UpperCAmelCase						)

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

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

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

							lowercase__	     =						torch.tensor([-4.1_739, -1.1_233, 3.1_205]						).to(_UpperCAmelCase						)

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








from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__UpperCamelCase:	Optional[int] = logging.get_logger(__name__)

__UpperCamelCase:	Optional[int] = {
    """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				"mobilenet_v1"

	def __init__(						self:						Dict,					lowerCamelCase_:						Any=3,					lowerCamelCase_:						Dict=224,					lowerCamelCase_:						int=1.0,					lowerCamelCase_:						List[Any]=8,					lowerCamelCase_:						int="relu6",					lowerCamelCase_:						Optional[int]=True,					lowerCamelCase_:						Any=0.9_9_9,					lowerCamelCase_:						List[str]=0.0_2,					lowerCamelCase_:						Optional[int]=0.0_0_1,					**lowerCamelCase_:						Tuple,					):
			super().__init__(**lowerCamelCase_			)

			if depth_multiplier <= 0:
					raise ValueError('depth_multiplier must be greater than zero.'			)

			lowercase__					:      Optional[int]      =		num_channels
			lowercase__					:      List[Any]      =		image_size
			lowercase__					:      str      =		depth_multiplier
			lowercase__					:      Optional[Any]      =		min_depth
			lowercase__					:      int      =		hidden_act
			lowercase__					:      Dict      =		tf_padding
			lowercase__					:      Optional[Any]      =		classifier_dropout_prob
			lowercase__					:      int      =		initializer_range
			lowercase__					:      Any      =		layer_norm_eps


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				version.parse("1.11"      )

	@property
	def    snake_case__(						self:						Optional[int]			):
			return OrderedDict([('pixel_values', {0: 'batch'})]			)

	@property
	def    snake_case__(						self:						Dict			):
			if self.task == "image-classification":
					return OrderedDict([('logits', {0: 'batch'})]			)
			else:
					return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})]			)





	@property
	def    snake_case__(						self:						List[Any]			):
			return 1E-4


