


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        _a							(			UpperCamelCase__			):

							def       lowerCamelCase_ (							self:	Optional[Any]							)			->   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							:

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





									"""simple docstring"""







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

							def       lowerCamelCase_ (							self:	Any							)			->   Dict:





									"""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:	Union[str, Any]							)			->   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       lowerCamelCase_ (							self:	Tuple    ,						UpperCamelCase_:	Tuple    ,						UpperCamelCase_:	Optional[Any]    ,						UpperCamelCase_:	List[Any]    ,						UpperCamelCase_:	List[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,
									    )    ,						)
									self.parent.assertEqual(
									    result.pooler_output.shape    ,						(self.batch_size, self.last_hidden_size)    ,						)

							def       lowerCamelCase_ (							self:	Any    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	Any    ,						UpperCamelCase_:	Optional[int]    ,						UpperCamelCase_:	List[Any]							)			->   Optional[int]:





									"""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]    ,						UpperCamelCase_:	Tuple    ,						UpperCamelCase_:	str    ,						UpperCamelCase_:	Any    ,						UpperCamelCase_:	List[str]							)			->   Optional[Any]:





									"""simple docstring"""







									lowercase__            =      self.num_labels
									lowercase__            =      MobileNetVaForSemanticSegmentation(UpperCamelCase_							)
									model.to(UpperCamelCase_							)
									model.eval()
									lowercase__            =      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,
									    )    ,						)
									lowercase__            =      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       lowerCamelCase_ (							self:	Optional[Any]							)			->   List[Any]:





									"""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			):
							_lowercase	:			str        = (
							    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							_lowercase	:			Any        = (
							    {
							        '''feature-extraction''': MobileNetVaModel,
							        '''image-classification''': MobileNetVaForImageClassification,
							        '''image-segmentation''': MobileNetVaForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							_lowercase	:			Dict        = False
							_lowercase	:			Any        = False
							_lowercase	:			List[str]        = False
							_lowercase	:			int        = False

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





									"""simple docstring"""







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

							def       lowerCamelCase_ (							self:	Any							)			->   Tuple:





									"""simple docstring"""







									self.config_tester.run_common_tests()

							@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''							)
							def       lowerCamelCase_ (							self:	Dict							)			->   Any:





									"""simple docstring"""







									pass

							@unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''							)
							def       lowerCamelCase_ (							self:	Any							)			->   Union[str, Any]:





									"""simple docstring"""







									pass

							@unittest.skip(reason='''MobileNetV2 does not output attentions'''							)
							def       lowerCamelCase_ (							self:	str							)			->   Optional[Any]:





									"""simple docstring"""







									pass

							def       lowerCamelCase_ (							self:	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:	Any							)			->   str:





									"""simple docstring"""







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

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





									"""simple docstring"""







									def check_hidden_states_output(UpperCamelCase_:	List[Any]    ,						UpperCamelCase_:	Union[str, Any]    ,						UpperCamelCase_:	List[str]							):
											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__            =      16
											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:	Union[str, Any]							)			->   Dict:





									"""simple docstring"""







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

							def       lowerCamelCase_ (							self:	Optional[Any]							)			->   Any:





									"""simple docstring"""







									lowercase__            =      self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase_							)


							@slow
							def       lowerCamelCase_ (							self:	Tuple							)			->   int:





									"""simple docstring"""







									for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowercase__            =      MobileNetVaModel.from_pretrained(UpperCamelCase_							)
											self.assertIsNotNone(UpperCamelCase_							)
def 			_a (      ):


		"""simple docstring"""




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


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

							@cached_property
							def       lowerCamelCase_ (							self:	List[Any]							)			->   Optional[Any]:





									"""simple docstring"""







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

							@slow
							def       lowerCamelCase_ (							self:	Optional[int]							)			->   str:





									"""simple docstring"""







									lowercase__            =      MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_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, 1_001)							)
									self.assertEqual(outputs.logits.shape    ,						UpperCamelCase_							)

									lowercase__            =      torch.tensor([0.2445, -1.1993, 0.1905]							).to(UpperCamelCase_							)

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


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





									"""simple docstring"""







									lowercase__            =      MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''							)
									lowercase__            =      model.to(UpperCamelCase_							)

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

									lowercase__            =      prepare_img()
									lowercase__            =      image_processor(images=UpperCamelCase_    ,						return_tensors='''pt'''							).to(UpperCamelCase_							)

									# forward pass
									with torch.no_grad():
											lowercase__            =      model(**UpperCamelCase_							)
									lowercase__            =      outputs.logits

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

									lowercase__            =      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							)							)






def 			_a (      SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		if exponent == 1:
				return base
		if exponent % 2 == 0:
				lowercase__            =      _modexpt(SCREAMING_SNAKE_CASE						,				exponent // 2						,				SCREAMING_SNAKE_CASE     ) % modulo_value
				return (x * x) % modulo_value
		else:
				return (base * _modexpt(SCREAMING_SNAKE_CASE						,				exponent - 1						,				SCREAMING_SNAKE_CASE     )) % modulo_value
def 			_a (      SCREAMING_SNAKE_CASE = 17_77						,				SCREAMING_SNAKE_CASE = 18_55						,				SCREAMING_SNAKE_CASE = 8     ):


		"""simple docstring"""




		lowercase__            =      base
		for _ in range(1						,				SCREAMING_SNAKE_CASE     ):
				lowercase__            =      _modexpt(SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE						,				10**digits     )

		return result


if __name__ == "__main__":
			print(f"""{solution() = }""")


