






"""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        lowercase__      (							snake_case__       ):


			def      UpperCAmelCase__						(				self					:  Dict ):
										lowerCamelCase_	:							Optional[int]									=self.config_class(**self.inputs_dict )
										self.parent.assertTrue(hasattr(snake_case__       ,	"tf_padding" ) )
										self.parent.assertTrue(hasattr(snake_case__       ,	"depth_multiplier" ) )







class        lowercase__      :


			def __init__(				self					:  Tuple       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  str=13       ,	snake_case__					:  int=3       ,	snake_case__					:  Optional[int]=32       ,	snake_case__					:  Tuple=0.25       ,	snake_case__					:  Optional[int]=8       ,	snake_case__					:  Optional[Any]=8       ,	snake_case__					:  int=6       ,	snake_case__					:  int=32       ,	snake_case__					:  List[Any]=True       ,	snake_case__					:  Optional[Any]=True       ,	snake_case__					:  Optional[int]=True       ,	snake_case__					:  Optional[Any]="relu6"       ,	snake_case__					:  Tuple=1280       ,	snake_case__					:  Any=0.1       ,	snake_case__					:  int=0.02       ,	snake_case__					:  Dict=True       ,	snake_case__					:  List[Any]=True       ,	snake_case__					:  Tuple=10       ,	snake_case__					:  Optional[Any]=None       ,	):
										lowerCamelCase_	:							Dict									=parent
										lowerCamelCase_	:							str									=batch_size
										lowerCamelCase_	:							List[str]									=num_channels
										lowerCamelCase_	:							Optional[int]									=image_size
										lowerCamelCase_	:							List[str]									=depth_multiplier
										lowerCamelCase_	:							List[str]									=depth_divisible_by
										lowerCamelCase_	:							Optional[int]									=min_depth
										lowerCamelCase_	:							Optional[Any]									=expand_ratio
										lowerCamelCase_	:							Optional[Any]									=tf_padding
										lowerCamelCase_	:							Union[str, Any]									=output_stride
										lowerCamelCase_	:							Any									=first_layer_is_expansion
										lowerCamelCase_	:							List[Any]									=finegrained_output
										lowerCamelCase_	:							int									=hidden_act
										lowerCamelCase_	:							Optional[int]									=last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier )
										lowerCamelCase_	:							List[str]									=classifier_dropout_prob
										lowerCamelCase_	:							Tuple									=use_labels
										lowerCamelCase_	:							Tuple									=is_training
										lowerCamelCase_	:							List[str]									=num_labels
										lowerCamelCase_	:							Optional[Any]									=initializer_range
										lowerCamelCase_	:							Any									=scope


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							Tuple									=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

										lowerCamelCase_	:							List[str]									=self.get_config()

										return config, pixel_values, labels, pixel_labels


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


			def      UpperCAmelCase__						(				self					:  Union[str, Any]       ,	snake_case__					:  str       ,	snake_case__					:  Union[str, Any]       ,	snake_case__					:  Tuple       ,	snake_case__					:  List[str] ):
										lowerCamelCase_	:							Dict									=self.num_labels
										lowerCamelCase_	:							Optional[Any]									=MobileNetVaForSemanticSegmentation(snake_case__ )
										model.to(snake_case__ )
										model.eval()
										lowerCamelCase_	:							str									=model(snake_case__ )
										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_	:							List[str]									=model(snake_case__       ,	labels=snake_case__ )
										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      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										lowerCamelCase_	:							Tuple									=self.prepare_config_and_inputs()
										lowerCamelCase_	:							int									=config_and_inputs
										lowerCamelCase_	:							List[str]									={"pixel_values": pixel_values}
										return config, inputs_dict







@require_torch
class        lowercase__      (							snake_case__,       snake_case__,       unittest.TestCase       ):
			_UpperCAmelCase		:Optional[int]             =			(
			    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			_UpperCAmelCase		:str             =			(
			    {
			        "feature-extraction": MobileNetVaModel,
			        "image-classification": MobileNetVaForImageClassification,
			        "image-segmentation": MobileNetVaForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			_UpperCAmelCase		:List[str]             =			False
			_UpperCAmelCase		:List[str]             =			False
			_UpperCAmelCase		:Union[str, Any]             =			False
			_UpperCAmelCase		:Dict             =			False


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							Tuple									=MobileNetVaModelTester(self )
										lowerCamelCase_	:							int									=MobileNetVaConfigTester(self       ,	config_class=snake_case__       ,	has_text_modality=snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[str] ):
										self.config_tester.run_common_tests()


			@unittest.skip(reason="MobileNetV2 does not use inputs_embeds" )
			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										pass


			@unittest.skip(reason="MobileNetV2 does not support input and output embeddings" )
			def      UpperCAmelCase__						(				self					:  str ):
										pass


			@unittest.skip(reason="MobileNetV2 does not output attentions" )
			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										pass


			def      UpperCAmelCase__						(				self					:  List[str] ):
										lowerCamelCase_	:							Union[str, Any]									=self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowerCamelCase_	:							Union[str, Any]									=["pixel_values"]
																	self.assertListEqual(arg_names[:1]       ,	snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[Any] ):
										lowerCamelCase_	:							Optional[int]									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[Any] ):
										def check_hidden_states_output(snake_case__					:  Union[str, Any]       ,	snake_case__					:  List[Any]       ,	snake_case__					:  Union[str, Any] ):
																	lowerCamelCase_	:							Tuple									=model_class(snake_case__ )
																	model.to(snake_case__ )
																	model.eval()

																	with torch.no_grad():
																								lowerCamelCase_	:							Optional[Any]									=model(**self._prepare_for_class(snake_case__       ,	snake_case__ ) )

																	lowerCamelCase_	:							List[Any]									=outputs.hidden_states

																	lowerCamelCase_	:							Union[str, Any]									=16
																	self.assertEqual(len(snake_case__ )       ,	snake_case__ )

										lowerCamelCase_	:							Tuple									=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowerCamelCase_	:							Dict									=True
																	check_hidden_states_output(snake_case__       ,	snake_case__       ,	snake_case__ )

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	lowerCamelCase_	:							int									=True

																	check_hidden_states_output(snake_case__       ,	snake_case__       ,	snake_case__ )


			def      UpperCAmelCase__						(				self					:  Any ):
										lowerCamelCase_	:							List[str]									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*snake_case__ )


			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										lowerCamelCase_	:							Optional[Any]									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__ )


			@slow
			def      UpperCAmelCase__						(				self					:  Dict ):
										for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowerCamelCase_	:							str									=MobileNetVaModel.from_pretrained(snake_case__ )
																	self.assertIsNotNone(snake_case__ )


def 			_snake_case    (					)    ->     Dict:
							lowerCamelCase_	:							str									=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
							return image







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


			@cached_property
			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										return (
										    MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None
										)


			@slow
			def      UpperCAmelCase__						(				self					:  Optional[Any] ):
										lowerCamelCase_	:							Optional[int]									=MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(snake_case__ )

										lowerCamelCase_	:							Any									=self.default_image_processor
										lowerCamelCase_	:							Tuple									=prepare_img()
										lowerCamelCase_	:							Union[str, Any]									=image_processor(images=snake_case__       ,	return_tensors="pt" ).to(snake_case__ )

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

										# verify the logits
										lowerCamelCase_	:							Optional[int]									=torch.Size((1, 1001) )
										self.assertEqual(outputs.logits.shape       ,	snake_case__ )

										lowerCamelCase_	:							int									=torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(snake_case__ )

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


			@slow
			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										lowerCamelCase_	:							Tuple									=MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" )
										lowerCamelCase_	:							Any									=model.to(snake_case__ )

										lowerCamelCase_	:							Any									=MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" )

										lowerCamelCase_	:							Tuple									=prepare_img()
										lowerCamelCase_	:							List[Any]									=image_processor(images=snake_case__       ,	return_tensors="pt" ).to(snake_case__ )

										# forward pass
										with torch.no_grad():
																	lowerCamelCase_	:							Dict									=model(**snake_case__ )
										lowerCamelCase_	:							str									=outputs.logits

										# verify the logits
										lowerCamelCase_	:							Dict									=torch.Size((1, 21, 65, 65) )
										self.assertEqual(logits.shape       ,	snake_case__ )

										lowerCamelCase_	:							Tuple									=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=snake_case__       ,	)

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












"""simple docstring"""



def 			_snake_case    (					lowerCamelCase__     :   list[list[int]]    ,						lowerCamelCase__     :   int    ,						lowerCamelCase__     :   int    ,						lowerCamelCase__     :   list[int]  )    ->     bool:

							# 1. Validate that path exists between current and next vertices
							if graph[path[curr_ind - 1]][next_ver] == 0:
														return False

							# 2. Validate that next vertex is not already in path
							return not any(vertex == next_ver for vertex in path  )

def 			_snake_case    (					lowerCamelCase__     :   list[list[int]]    ,						lowerCamelCase__     :   list[int]    ,						lowerCamelCase__     :   int  )    ->     bool:

							# Base Case
							if curr_ind == len(lowerCamelCase__  ):
														# return whether path exists between current and starting vertices
														return graph[path[curr_ind - 1]][path[0]] == 1

							# Recursive Step
							for next_ver in range(0    ,						len(lowerCamelCase__  )  ):
														if valid_connection(lowerCamelCase__    ,						lowerCamelCase__    ,						lowerCamelCase__    ,						lowerCamelCase__  ):
																					# Insert current vertex  into path as next transition
																					lowerCamelCase_	:							Tuple									=next_ver
																					# Validate created path
																					if util_hamilton_cycle(lowerCamelCase__    ,						lowerCamelCase__    ,						curr_ind + 1  ):
																												return True
																					# Backtrack
																					lowerCamelCase_	:							int									=-1
							return False

def 			_snake_case    (					lowerCamelCase__     :   list[list[int]]    ,						lowerCamelCase__     :   int = 0  )    ->     list[int]:
							lowerCamelCase_	:							Optional[Any]									=[-1] * (len(lowerCamelCase__  ) + 1)
							# initialize start and end of path with starting index
							lowerCamelCase_	:							Optional[int]									=start_index
							# evaluate and if we find answer return path either return empty array
							return path if util_hamilton_cycle(lowerCamelCase__    ,						lowerCamelCase__    ,						1  ) else []



