






"""simple docstring"""



import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
						from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import MobileViTImageProcessor







class        lowercase__      (							snake_case__       ):


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							List[str]									=self.config_class(**self.inputs_dict )
										self.parent.assertTrue(hasattr(snake_case__       ,	"hidden_sizes" ) )
										self.parent.assertTrue(hasattr(snake_case__       ,	"neck_hidden_sizes" ) )
										self.parent.assertTrue(hasattr(snake_case__       ,	"num_attention_heads" ) )







class        lowercase__      :


			def __init__(				self					:  Dict       ,	snake_case__					:  List[str]       ,	snake_case__					:  List[str]=13       ,	snake_case__					:  Dict=32       ,	snake_case__					:  Tuple=2       ,	snake_case__					:  int=3       ,	snake_case__					:  Dict=640       ,	snake_case__					:  Optional[Any]=4       ,	snake_case__					:  str="silu"       ,	snake_case__					:  str=3       ,	snake_case__					:  Optional[Any]=32       ,	snake_case__					:  Tuple=0.1       ,	snake_case__					:  Tuple=0.1       ,	snake_case__					:  Dict=0.1       ,	snake_case__					:  Any=0.02       ,	snake_case__					:  int=True       ,	snake_case__					:  Tuple=True       ,	snake_case__					:  Any=10       ,	snake_case__					:  List[Any]=None       ,	):
										lowerCamelCase_	:							List[Any]									=parent
										lowerCamelCase_	:							Any									=batch_size
										lowerCamelCase_	:							Any									=image_size
										lowerCamelCase_	:							Tuple									=patch_size
										lowerCamelCase_	:							List[Any]									=num_channels
										lowerCamelCase_	:							int									=last_hidden_size
										lowerCamelCase_	:							Any									=num_attention_heads
										lowerCamelCase_	:							Tuple									=hidden_act
										lowerCamelCase_	:							Any									=conv_kernel_size
										lowerCamelCase_	:							Optional[int]									=output_stride
										lowerCamelCase_	:							str									=hidden_dropout_prob
										lowerCamelCase_	:							int									=attention_probs_dropout_prob
										lowerCamelCase_	:							Tuple									=classifier_dropout_prob
										lowerCamelCase_	:							Optional[Any]									=use_labels
										lowerCamelCase_	:							List[str]									=is_training
										lowerCamelCase_	:							Tuple									=num_labels
										lowerCamelCase_	:							List[Any]									=initializer_range
										lowerCamelCase_	:							int									=scope


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

										lowerCamelCase_	:							int									=None
										lowerCamelCase_	:							str									=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_	:							int									=self.get_config()

										return config, pixel_values, labels, pixel_labels


			def      UpperCAmelCase__						(				self					:  str ):
										return MobileViTConfig(
										    image_size=self.image_size       ,	patch_size=self.patch_size       ,	num_channels=self.num_channels       ,	num_attention_heads=self.num_attention_heads       ,	hidden_act=self.hidden_act       ,	conv_kernel_size=self.conv_kernel_size       ,	output_stride=self.output_stride       ,	hidden_dropout_prob=self.hidden_dropout_prob       ,	attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,	classifier_dropout_prob=self.classifier_dropout_prob       ,	initializer_range=self.initializer_range       ,	)


			def      UpperCAmelCase__						(				self					:  Union[str, Any]       ,	snake_case__					:  Tuple       ,	snake_case__					:  List[str]       ,	snake_case__					:  str       ,	snake_case__					:  Tuple ):
										lowerCamelCase_	:							Tuple									=MobileViTModel(config=snake_case__ )
										model.to(snake_case__ )
										model.eval()
										lowerCamelCase_	:							Tuple									=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,
										    )       ,	)


			def      UpperCAmelCase__						(				self					:  int       ,	snake_case__					:  Optional[int]       ,	snake_case__					:  List[Any]       ,	snake_case__					:  Union[str, Any]       ,	snake_case__					:  List[Any] ):
										lowerCamelCase_	:							Optional[Any]									=self.num_labels
										lowerCamelCase_	:							List[str]									=MobileViTForImageClassification(snake_case__ )
										model.to(snake_case__ )
										model.eval()
										lowerCamelCase_	:							Any									=model(snake_case__       ,	labels=snake_case__ )
										self.parent.assertEqual(result.logits.shape       ,	(self.batch_size, self.num_labels) )


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







@require_torch
class        lowercase__      (							snake_case__,       snake_case__,       unittest.TestCase       ):
			_UpperCAmelCase		:Union[str, Any]             =			(
			    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			_UpperCAmelCase		:List[Any]             =			(
			    {
			        "feature-extraction": MobileViTModel,
			        "image-classification": MobileViTForImageClassification,
			        "image-segmentation": MobileViTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			_UpperCAmelCase		:int             =			False
			_UpperCAmelCase		:Any             =			False
			_UpperCAmelCase		:Tuple             =			False
			_UpperCAmelCase		:Tuple             =			False


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							str									=MobileViTModelTester(self )
										lowerCamelCase_	:							Optional[int]									=MobileViTConfigTester(self       ,	config_class=snake_case__       ,	has_text_modality=snake_case__ )


			def      UpperCAmelCase__						(				self					:  Dict ):
										self.config_tester.run_common_tests()


			@unittest.skip(reason="MobileViT does not use inputs_embeds" )
			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										pass


			@unittest.skip(reason="MobileViT does not support input and output embeddings" )
			def      UpperCAmelCase__						(				self					:  List[Any] ):
										pass


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


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

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

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


			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
			def      UpperCAmelCase__						(				self					:  List[Any] ):
										pass


			def      UpperCAmelCase__						(				self					:  Tuple ):
										lowerCamelCase_	:							Any									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*snake_case__ )


			def      UpperCAmelCase__						(				self					:  int ):
										def check_hidden_states_output(snake_case__					:  List[Any]       ,	snake_case__					:  Any       ,	snake_case__					:  Any ):
																	lowerCamelCase_	:							Any									=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_	:							str									=outputs.hidden_states

																	lowerCamelCase_	:							Dict									=5
																	self.assertEqual(len(snake_case__ )       ,	snake_case__ )

																	# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
																	# with the width and height being successively divided by 2.
																	lowerCamelCase_	:							Union[str, Any]									=2
																	for i in range(len(snake_case__ ) ):
																								self.assertListEqual(
																								    list(hidden_states[i].shape[-2:] )       ,	[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]       ,	)
																								divisor *= 2

																	self.assertEqual(self.model_tester.output_stride       ,	divisor // 2 )

										lowerCamelCase_							,						lowerCamelCase_	:							Optional[Any]									=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	lowerCamelCase_	:							str									=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_	:							List[Any]									=True

																	check_hidden_states_output(snake_case__       ,	snake_case__       ,	snake_case__ )


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


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


			@slow
			def      UpperCAmelCase__						(				self					:  Optional[Any] ):
										for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowerCamelCase_	:							Union[str, Any]									=MobileViTModel.from_pretrained(snake_case__ )
																	self.assertIsNotNone(snake_case__ )


def 			_snake_case    (					)    ->     Tuple:
							lowerCamelCase_	:							int									=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[Any] ):
										return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None


			@slow
			def      UpperCAmelCase__						(				self					:  int ):
										lowerCamelCase_	:							Dict									=MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(snake_case__ )

										lowerCamelCase_	:							Any									=self.default_image_processor
										lowerCamelCase_	:							Any									=prepare_img()
										lowerCamelCase_	:							int									=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_	:							int									=torch.Size((1, 1000) )
										self.assertEqual(outputs.logits.shape       ,	snake_case__ )

										lowerCamelCase_	:							Optional[int]									=torch.tensor([-1.9_364, -1.2_327, -0.4_653] ).to(snake_case__ )

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


			@slow
			def      UpperCAmelCase__						(				self					:  Dict ):
										lowerCamelCase_	:							Tuple									=MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
										lowerCamelCase_	:							Tuple									=model.to(snake_case__ )

										lowerCamelCase_	:							Any									=MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )

										lowerCamelCase_	:							Dict									=prepare_img()
										lowerCamelCase_	:							Optional[int]									=image_processor(images=snake_case__       ,	return_tensors="pt" ).to(snake_case__ )

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

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

										lowerCamelCase_	:							Optional[int]									=torch.tensor(
										    [
										        [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
										        [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
										        [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
										    ]       ,	device=snake_case__       ,	)

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


			@slow
			def      UpperCAmelCase__						(				self					:  Optional[Any] ):
										lowerCamelCase_	:							Any									=MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
										lowerCamelCase_	:							Tuple									=model.to(snake_case__ )

										lowerCamelCase_	:							List[str]									=MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )

										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_	:							str									=model(**snake_case__ )

										lowerCamelCase_	:							int									=outputs.logits.detach().cpu()

										lowerCamelCase_	:							Optional[Any]									=image_processor.post_process_semantic_segmentation(outputs=snake_case__       ,	target_sizes=[(50, 60)] )
										lowerCamelCase_	:							Dict									=torch.Size((50, 60) )
										self.assertEqual(segmentation[0].shape       ,	snake_case__ )

										lowerCamelCase_	:							Optional[int]									=image_processor.post_process_semantic_segmentation(outputs=snake_case__ )
										lowerCamelCase_	:							Optional[Any]									=torch.Size((32, 32) )
										self.assertEqual(segmentation[0].shape       ,	snake_case__ )











"""simple docstring"""



from __future__ import annotations

from collections import namedtuple

def 			_snake_case    (					lowerCamelCase__     :   float    ,						lowerCamelCase__     :   float    ,						lowerCamelCase__     :   float  )    ->     tuple:
							lowerCamelCase_	:							Optional[Any]									=namedtuple("result"    ,						"name value"  )
							if (voltage, current, power).count(0  ) != 1:
														raise ValueError("Only one argument must be 0"  )
							elif power < 0:
														raise ValueError(
														    "Power cannot be negative in any electrical/electronics system"  )
							elif voltage == 0:
														return result("voltage"    ,						power / current  )
							elif current == 0:
														return result("current"    ,						power / voltage  )
							elif power == 0:
														return result("power"    ,						float(round(abs(voltage * current  )    ,						2  )  )  )
							else:
														raise ValueError("Exactly one argument must be 0"  )


if __name__ == "__main__":
						import doctest

						doctest.testmod()



