





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     _UpperCAmelCase   (   _UpperCamelCase   ):

		"""simple docstring"""


		def     lowercase		(    self			:		Any					)							->						str:
					__lowerCAmelCase							     =     self.config_class(**self.inputs_dict					)
					self.parent.assertTrue(hasattr(lowerCAmelCase_ ,  'tf_padding'					)					)
					self.parent.assertTrue(hasattr(lowerCAmelCase_ ,  'depth_multiplier'					)					)





class     _UpperCAmelCase   :

		"""simple docstring"""


		def __init__(    self			:		Optional[Any] ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		Dict=1_3 ,  lowerCAmelCase_			:		Optional[Any]=3 ,  lowerCAmelCase_			:		Optional[int]=3_2 ,  lowerCAmelCase_			:		int=0.25 ,  lowerCAmelCase_			:		Any=8 ,  lowerCAmelCase_			:		Dict=True ,  lowerCAmelCase_			:		Tuple=1_0_2_4 ,  lowerCAmelCase_			:		int=3_2 ,  lowerCAmelCase_			:		Optional[int]="relu6" ,  lowerCAmelCase_			:		List[str]=0.1 ,  lowerCAmelCase_			:		str=0.02 ,  lowerCAmelCase_			:		Optional[int]=True ,  lowerCAmelCase_			:		Optional[int]=True ,  lowerCAmelCase_			:		List[Any]=1_0 ,  lowerCAmelCase_			:		Union[str, Any]=None ,  )							->						List[Any]:
					__lowerCAmelCase							     =     parent
					__lowerCAmelCase							     =     batch_size
					__lowerCAmelCase							     =     num_channels
					__lowerCAmelCase							     =     image_size
					__lowerCAmelCase							     =     depth_multiplier
					__lowerCAmelCase							     =     min_depth
					__lowerCAmelCase							     =     tf_padding
					__lowerCAmelCase							     =     int(last_hidden_size * depth_multiplier					)
					__lowerCAmelCase							     =     output_stride
					__lowerCAmelCase							     =     hidden_act
					__lowerCAmelCase							     =     classifier_dropout_prob
					__lowerCAmelCase							     =     use_labels
					__lowerCAmelCase							     =     is_training
					__lowerCAmelCase							     =     num_labels
					__lowerCAmelCase							     =     initializer_range
					__lowerCAmelCase							     =     scope






		def     lowercase		(    self			:		List[str]					)							->						List[Any]:
					__lowerCAmelCase							     =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

					__lowerCAmelCase							     =     self.get_config()

					return config, pixel_values, labels, pixel_labels






		def     lowercase		(    self			:		Optional[int]					)							->						Tuple:
					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     lowercase		(    self			:		Tuple ,  lowerCAmelCase_			:		List[Any] ,  lowerCAmelCase_			:		Union[str, Any] ,  lowerCAmelCase_			:		Tuple ,  lowerCAmelCase_			:		Tuple					)							->						List[str]:
					__lowerCAmelCase							     =     MobileNetVaModel(config=lowerCAmelCase_					)
					model.to(lowerCAmelCase_					)
					model.eval()
					__lowerCAmelCase							     =     model(lowerCAmelCase_					)
					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     lowercase		(    self			:		Optional[int] ,  lowerCAmelCase_			:		int ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		Union[str, Any]					)							->						Dict:
					__lowerCAmelCase							     =     self.num_labels
					__lowerCAmelCase							     =     MobileNetVaForImageClassification(lowerCAmelCase_					)
					model.to(lowerCAmelCase_					)
					model.eval()
					__lowerCAmelCase							     =     model(lowerCAmelCase_ ,  labels=lowerCAmelCase_					)
					self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels)					)






		def     lowercase		(    self			:		int					)							->						Tuple:
					__lowerCAmelCase							     =     self.prepare_config_and_inputs()
					__lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     config_and_inputs
					__lowerCAmelCase							     =     {'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class     _UpperCAmelCase   (   _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     lowercase		(    self			:		Optional[Any]					)							->						Any:
					__lowerCAmelCase							     =     MobileNetVaModelTester(self					)
					__lowerCAmelCase							     =     MobileNetVaConfigTester(self ,  config_class=lowerCAmelCase_ ,  has_text_modality=lowerCAmelCase_					)






		def     lowercase		(    self			:		Optional[Any]					)							->						int:
					self.config_tester.run_common_tests()






		@unittest.skip(reason='MobileNetV1 does not use inputs_embeds'					)
		def     lowercase		(    self			:		Dict					)							->						Dict:
					pass






		@unittest.skip(reason='MobileNetV1 does not support input and output embeddings'					)
		def     lowercase		(    self			:		Any					)							->						List[Any]:
					pass






		@unittest.skip(reason='MobileNetV1 does not output attentions'					)
		def     lowercase		(    self			:		Union[str, Any]					)							->						List[Any]:
					pass






		def     lowercase		(    self			:		Dict					)							->						Tuple:
					__lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

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

								__lowerCAmelCase							     =     ['pixel_values']
								self.assertListEqual(arg_names[:1] ,  lowerCAmelCase_					)






		def     lowercase		(    self			:		List[Any]					)							->						Optional[Any]:
					__lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCAmelCase_					)






		def     lowercase		(    self			:		List[Any]					)							->						Dict:
					def check_hidden_states_output(lowerCAmelCase_			:		Dict ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		Union[str, Any]					):
								__lowerCAmelCase							     =     model_class(lowerCAmelCase_					)
								model.to(lowerCAmelCase_					)
								model.eval()

								with torch.no_grad():
											__lowerCAmelCase							     =     model(**self._prepare_for_class(lowerCAmelCase_ ,  lowerCAmelCase_					)					)

								__lowerCAmelCase							     =     outputs.hidden_states

								__lowerCAmelCase							     =     2_6
								self.assertEqual(len(lowerCAmelCase_					) ,  lowerCAmelCase_					)

					__lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__lowerCAmelCase							     =     True
								check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)

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

								check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)






		def     lowercase		(    self			:		Tuple					)							->						int:
					__lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_					)






		@slow
		def     lowercase		(    self			:		Any					)							->						str:
					for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__lowerCAmelCase							     =     MobileNetVaModel.from_pretrained(lowerCAmelCase_					)
								self.assertIsNotNone(lowerCAmelCase_					)





def   a_   (			):
			__lowerCAmelCase							     =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
			return image




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

		"""simple docstring"""


		@cached_property
		def     lowercase		(    self			:		Any					)							->						Optional[Any]:
					return (
					    MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'					) if is_vision_available() else None
					)






		@slow
		def     lowercase		(    self			:		Optional[int]					)							->						List[str]:
					__lowerCAmelCase							     =     MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'					).to(lowerCAmelCase_					)

					__lowerCAmelCase							     =     self.default_image_processor
					__lowerCAmelCase							     =     prepare_img()
					__lowerCAmelCase							     =     image_processor(images=lowerCAmelCase_ ,  return_tensors='pt'					).to(lowerCAmelCase_					)

					# forward pass
					with torch.no_grad():
								__lowerCAmelCase							     =     model(**lowerCAmelCase_					)

					# verify the logits
					__lowerCAmelCase							     =     torch.Size((1, 1_0_0_1)					)
					self.assertEqual(outputs.logits.shape ,  lowerCAmelCase_					)

					__lowerCAmelCase							     =     torch.tensor([-4.17_39, -1.12_33, 3.12_05]					).to(lowerCAmelCase_					)

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








from functools import lru_cache

@lru_cache
def   a_   (			lowerCAmelCase_				:      int     ):
   if num < 0:
      raise ValueError('Number should not be negative.'     )

   return 1 if num in (0, 1) else num * factorial(num - 1     )


if __name__ == "__main__":
     import doctest

     doctest.testmod()

