





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    (    lowerCAmelCase ):

			'''simple docstring'''







			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.config_class(**self.inputs_dict							)
				self.parent.assertTrue(hasattr(__lowerCAmelCase       ,  '''tf_padding'''							)							)
				self.parent.assertTrue(hasattr(__lowerCAmelCase       ,  '''depth_multiplier'''							)							)






class 					__A    :

			'''simple docstring'''







			def __init__(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase=1_3       ,  __lowerCAmelCase=3       ,  __lowerCAmelCase=3_2       ,  __lowerCAmelCase=0.25       ,  __lowerCAmelCase=8       ,  __lowerCAmelCase=8       ,  __lowerCAmelCase=6       ,  __lowerCAmelCase=3_2       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase="relu6"       ,  __lowerCAmelCase=1_2_8_0       ,  __lowerCAmelCase=0.1       ,  __lowerCAmelCase=0.02       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=1_0       ,  __lowerCAmelCase=None       ,  ):



				'''simple docstring'''







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





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				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 		__lowerCamelCase				(    self							):



				'''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       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				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,
				    )       ,  )
				self.parent.assertEqual(
				    result.pooler_output.shape       ,  (self.batch_size, self.last_hidden_size)       ,  )





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				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 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		self.num_labels
				lowerCamelCase__								=		MobileNetVaForSemanticSegmentation(__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase							)
				self.parent.assertEqual(
				    result.logits.shape       ,  (
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )       ,  )
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  labels=__lowerCAmelCase							)
				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							):



				'''simple docstring'''







				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 					__A    (    lowerCAmelCase			,				lowerCAmelCase			,				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 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		MobileNetVaModelTester(self							)
				lowerCamelCase__								=		MobileNetVaConfigTester(self       ,  config_class=__lowerCAmelCase       ,  has_text_modality=__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				self.config_tester.run_common_tests()





			@unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''							)
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				pass





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



				'''simple docstring'''







				pass





			@unittest.skip(reason='''MobileNetV2 does not output attentions'''							)
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				pass





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				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 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				def check_hidden_states_output(__lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):
					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__								=		1_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 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCAmelCase							)





			@slow
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







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





def lowerCAmelCase__()				->      Dict:







	'''simple docstring'''







	lowerCamelCase__								=		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							):



				'''simple docstring'''







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





			@slow
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_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([0.2445, -1.1993, 0.1905]							).to(__lowerCAmelCase							)

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





			@slow
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''							)
				lowerCamelCase__								=		model.to(__lowerCAmelCase							)

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

				lowerCamelCase__								=		prepare_img()
				lowerCamelCase__								=		image_processor(images=__lowerCAmelCase       ,  return_tensors='''pt'''							).to(__lowerCAmelCase							)

				# forward pass
				with torch.no_grad():
					lowerCamelCase__								=		model(**__lowerCAmelCase							)
				lowerCamelCase__								=		outputs.logits

				# verify the logits
				lowerCamelCase__								=		torch.Size((1, 2_1, 6_5, 6_5)							)
				self.assertEqual(logits.shape       ,  __lowerCAmelCase							)

				lowerCamelCase__								=		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=__lowerCAmelCase       ,  )

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










import pytest

from datasets.parallel import ParallelBackendConfig, parallel_backend
from datasets.utils.py_utils import map_nested

from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows





def lowerCAmelCase__(__snake_case							)				->      int:  # picklable for multiprocessing







	'''simple docstring'''







	return i + 1





@require_dill_gt_0_3_2
@require_joblibspark
@require_not_windows
def lowerCAmelCase__()				->      Any:







	'''simple docstring'''







	with parallel_backend('''spark'''							):
		assert ParallelBackendConfig.backend_name == "spark"

	lowerCamelCase__								=		[1, 2, 3]
	with pytest.raises(__snake_case							):
		with parallel_backend('''unsupported backend'''							):
			map_nested(__snake_case       ,__snake_case       ,num_proc=2							)

	with pytest.raises(__snake_case							):
		with parallel_backend('''unsupported backend'''							):
			map_nested(__snake_case       ,__snake_case       ,num_proc=-1							)





@require_dill_gt_0_3_2
@require_joblibspark
@require_not_windows
@pytest.mark.parametrize('''num_proc'''       ,[2, -1]							)
def lowerCAmelCase__(__snake_case							)				->      Tuple:







	'''simple docstring'''







	lowerCamelCase__								=		[1, 2]
	lowerCamelCase__								=		{'''a''': 1, '''b''': 2}
	lowerCamelCase__								=		{'''a''': [1, 2], '''b''': [3, 4]}
	lowerCamelCase__								=		{'''a''': {'''1''': 1}, '''b''': 2}
	lowerCamelCase__								=		{'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}
	lowerCamelCase__								=		[2, 3]
	lowerCamelCase__								=		{'''a''': 2, '''b''': 3}
	lowerCamelCase__								=		{'''a''': [2, 3], '''b''': [4, 5]}
	lowerCamelCase__								=		{'''a''': {'''1''': 2}, '''b''': 3}
	lowerCamelCase__								=		{'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}

	with parallel_backend('''spark'''							):
		assert map_nested(__snake_case       ,__snake_case       ,num_proc=__snake_case							) == expected_map_nested_sa
		assert map_nested(__snake_case       ,__snake_case       ,num_proc=__snake_case							) == expected_map_nested_sa
		assert map_nested(__snake_case       ,__snake_case       ,num_proc=__snake_case							) == expected_map_nested_sa
		assert map_nested(__snake_case       ,__snake_case       ,num_proc=__snake_case							) == expected_map_nested_sa
		assert map_nested(__snake_case       ,__snake_case       ,num_proc=__snake_case							) == expected_map_nested_sa



