


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

				"""simple docstring"""




				def    lowercase__							(	self )    ->      str:







					"""simple docstring"""






					snake_case__			:			Dict             =		self.config_class(**self.inputs_dict )
					self.parent.assertTrue(hasattr(A_       ,    '''tf_padding''' ) )
					self.parent.assertTrue(hasattr(A_       ,    '''depth_multiplier''' ) )



class 		snake_case				:

				"""simple docstring"""




				def __init__(	self       ,    lowerCamelCase       ,    lowerCamelCase=13       ,    lowerCamelCase=3       ,    lowerCamelCase=32       ,    lowerCamelCase=0.25       ,    lowerCamelCase=8       ,    lowerCamelCase=8       ,    lowerCamelCase=6       ,    lowerCamelCase=32       ,    lowerCamelCase=True       ,    lowerCamelCase=True       ,    lowerCamelCase=True       ,    lowerCamelCase="relu6"       ,    lowerCamelCase=1280       ,    lowerCamelCase=0.1       ,    lowerCamelCase=0.02       ,    lowerCamelCase=True       ,    lowerCamelCase=True       ,    lowerCamelCase=10       ,    lowerCamelCase=None       ,    )    ->      Optional[int]:







					"""simple docstring"""






					snake_case__			:			str             =		parent
					snake_case__			:			Any             =		batch_size
					snake_case__			:			Tuple             =		num_channels
					snake_case__			:			Optional[int]             =		image_size
					snake_case__			:			Union[str, Any]             =		depth_multiplier
					snake_case__			:			Union[str, Any]             =		depth_divisible_by
					snake_case__			:			List[Any]             =		min_depth
					snake_case__			:			str             =		expand_ratio
					snake_case__			:			Any             =		tf_padding
					snake_case__			:			Optional[Any]             =		output_stride
					snake_case__			:			int             =		first_layer_is_expansion
					snake_case__			:			Optional[int]             =		finegrained_output
					snake_case__			:			List[str]             =		hidden_act
					snake_case__			:			Union[str, Any]             =		last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier )
					snake_case__			:			Dict             =		classifier_dropout_prob
					snake_case__			:			Dict             =		use_labels
					snake_case__			:			Optional[int]             =		is_training
					snake_case__			:			List[Any]             =		num_labels
					snake_case__			:			List[str]             =		initializer_range
					snake_case__			:			Dict             =		scope





				def    lowercase__							(	self )    ->      Tuple:







					"""simple docstring"""






					snake_case__			:			Union[str, Any]             =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

					snake_case__			:			Optional[int]             =		None
					snake_case__			:			Union[str, Any]             =		None
					if self.use_labels:
						snake_case__			:			str             =		ids_tensor([self.batch_size]       ,    self.num_labels )
						snake_case__			:			Optional[int]             =		ids_tensor([self.batch_size, self.image_size, self.image_size]       ,    self.num_labels )

					snake_case__			:			str             =		self.get_config()

					return config, pixel_values, labels, pixel_labels





				def    lowercase__							(	self )    ->      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       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase )    ->      int:







					"""simple docstring"""






					snake_case__			:			int             =		MobileNetVaModel(config=A_ )
					model.to(A_ )
					model.eval()
					snake_case__			:			str             =		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       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase )    ->      str:







					"""simple docstring"""






					snake_case__			:			Optional[int]             =		self.num_labels
					snake_case__			:			Optional[Any]             =		MobileNetVaForImageClassification(A_ )
					model.to(A_ )
					model.eval()
					snake_case__			:			str             =		model(A_       ,    labels=A_ )
					self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.num_labels) )





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







					"""simple docstring"""






					snake_case__			:			Optional[int]             =		self.num_labels
					snake_case__			:			Optional[Any]             =		MobileNetVaForSemanticSegmentation(A_ )
					model.to(A_ )
					model.eval()
					snake_case__			:			Optional[int]             =		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,
					    )       ,    )
					snake_case__			:			str             =		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"""






					snake_case__			:			Optional[Any]             =		self.prepare_config_and_inputs()
					snake_case__      ,snake_case__      ,snake_case__      ,snake_case__			:			List[str]             =		config_and_inputs
					snake_case__			:			List[str]             =		{'''pixel_values''': pixel_values}
					return config, inputs_dict



@require_torch
class 		snake_case				(    _a				,    _a				,    unittest.TestCase						):

				"""simple docstring"""




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

				_lowerCAmelCase           =    False
				_lowerCAmelCase           =    False
				_lowerCAmelCase           =    False
				_lowerCAmelCase           =    False





				def    lowercase__							(	self )    ->      Tuple:







					"""simple docstring"""






					snake_case__			:			str             =		MobileNetVaModelTester(self )
					snake_case__			:			Optional[int]             =		MobileNetVaConfigTester(self       ,    config_class=A_       ,    has_text_modality=A_ )





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







					"""simple docstring"""






					self.config_tester.run_common_tests()





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







					"""simple docstring"""






					pass





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







					"""simple docstring"""






					pass





				@unittest.skip(reason='''MobileNetV2 does not output attentions''' )
				def    lowercase__							(	self )    ->      int:







					"""simple docstring"""






					pass





				def    lowercase__							(	self )    ->      int:







					"""simple docstring"""






					snake_case__      ,snake_case__			:			str             =		self.model_tester.prepare_config_and_inputs_for_common()

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

						snake_case__			:			str             =		['''pixel_values''']
						self.assertListEqual(arg_names[:1]       ,    A_ )





				def    lowercase__							(	self )    ->      int:







					"""simple docstring"""






					snake_case__			:			List[str]             =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*A_ )





				def    lowercase__							(	self )    ->      Any:







					"""simple docstring"""






					def check_hidden_states_output(lowerCamelCase       ,    lowerCamelCase       ,    lowerCamelCase ):
						snake_case__			:			Optional[int]             =		model_class(A_ )
						model.to(A_ )
						model.eval()

						with torch.no_grad():
							snake_case__			:			int             =		model(**self._prepare_for_class(A_       ,    A_ ) )

						snake_case__			:			Optional[Any]             =		outputs.hidden_states

						snake_case__			:			Any             =		16
						self.assertEqual(len(A_ )       ,    A_ )

					snake_case__      ,snake_case__			:			Tuple             =		self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						snake_case__			:			Optional[int]             =		True
						check_hidden_states_output(A_       ,    A_       ,    A_ )

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						snake_case__			:			List[str]             =		True

						check_hidden_states_output(A_       ,    A_       ,    A_ )





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







					"""simple docstring"""






					snake_case__			:			Any             =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*A_ )





				def    lowercase__							(	self )    ->      str:







					"""simple docstring"""






					snake_case__			:			Any             =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*A_ )





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







					"""simple docstring"""






					for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						snake_case__			:			Tuple             =		MobileNetVaModel.from_pretrained(A_ )
						self.assertIsNotNone(A_ )






def 					_A			(			):
	snake_case__			:			Union[str, Any]             =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
	return image





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

				"""simple docstring"""




				@cached_property
				def    lowercase__							(	self )    ->      Any:







					"""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"""






					snake_case__			:			int             =		MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224''' ).to(A_ )

					snake_case__			:			Union[str, Any]             =		self.default_image_processor
					snake_case__			:			Dict             =		prepare_img()
					snake_case__			:			Union[str, Any]             =		image_processor(images=A_       ,    return_tensors='''pt''' ).to(A_ )

					# forward pass
					with torch.no_grad():
						snake_case__			:			str             =		model(**A_ )

					# verify the logits
					snake_case__			:			Dict             =		torch.Size((1, 1001) )
					self.assertEqual(outputs.logits.shape       ,    A_ )

					snake_case__			:			Optional[Any]             =		torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(A_ )

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





				@slow
				def    lowercase__							(	self )    ->      int:







					"""simple docstring"""






					snake_case__			:			Optional[Any]             =		MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )
					snake_case__			:			Dict             =		model.to(A_ )

					snake_case__			:			Dict             =		MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )

					snake_case__			:			Any             =		prepare_img()
					snake_case__			:			int             =		image_processor(images=A_       ,    return_tensors='''pt''' ).to(A_ )

					# forward pass
					with torch.no_grad():
						snake_case__			:			Union[str, Any]             =		model(**A_ )
					snake_case__			:			Any             =		outputs.logits

					# verify the logits
					snake_case__			:			Optional[Any]             =		torch.Size((1, 21, 65, 65) )
					self.assertEqual(logits.shape       ,    A_ )

					snake_case__			:			Union[str, Any]             =		torch.tensor(
					    [
					        [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
					        [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]],
					        [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]],
					    ]       ,    device=A_       ,    )

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









"""simple docstring"""

def lowerCAmelCase_   (					UpperCamelCase__						:			int			):






 """simple docstring"""







 assert (
     isinstance(UpperCamelCase__					, UpperCamelCase__			) and number_of_steps > 0
 ), f'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
 if number_of_steps == 1:
  return 1
 __lowercase				,		__lowercase						=						1, 1
 for _ in range(number_of_steps - 1			):
  __lowercase				,		__lowercase						=						current + previous, current
 return current


if __name__ == "__main__":
       import doctest

       doctest.testmod()
