




import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
			from transformers.models.mobilevitva.modeling_mobilevitva import (
			    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
			    make_divisible,
			)


if is_vision_available():
			from PIL import Image

			from transformers import MobileViTImageProcessor






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				def     _A							(							self:   int		):
											SCREAMING_SNAKE_CASE_   	=    self.config_class(**self.inputs_dict		)
											self.parent.assertTrue(hasattr(_lowerCamelCase		,					'''width_multiplier'''		)		)






class  __magic_name__						:
				'''simple docstring'''







				def __init__(							self:   Any		,					_lowerCamelCase:   str		,					_lowerCamelCase:   List[str]=13		,					_lowerCamelCase:   str=64		,					_lowerCamelCase:   str=2		,					_lowerCamelCase:   Tuple=3		,					_lowerCamelCase:   Tuple="swish"		,					_lowerCamelCase:   Tuple=3		,					_lowerCamelCase:   Dict=32		,					_lowerCamelCase:   Tuple=0.1		,					_lowerCamelCase:   Union[str, Any]=0.02		,					_lowerCamelCase:   Tuple=True		,					_lowerCamelCase:   Optional[int]=True		,					_lowerCamelCase:   Union[str, Any]=10		,					_lowerCamelCase:   Tuple=None		,					_lowerCamelCase:   str=0.25		,					_lowerCamelCase:   str=0.0		,					_lowerCamelCase:   int=0.0		,					):
											SCREAMING_SNAKE_CASE_   	=    parent
											SCREAMING_SNAKE_CASE_   	=    batch_size
											SCREAMING_SNAKE_CASE_   	=    image_size
											SCREAMING_SNAKE_CASE_   	=    patch_size
											SCREAMING_SNAKE_CASE_   	=    num_channels
											SCREAMING_SNAKE_CASE_   	=    make_divisible(5_12 * width_multiplier		,					divisor=8		)
											SCREAMING_SNAKE_CASE_   	=    hidden_act
											SCREAMING_SNAKE_CASE_   	=    conv_kernel_size
											SCREAMING_SNAKE_CASE_   	=    output_stride
											SCREAMING_SNAKE_CASE_   	=    classifier_dropout_prob
											SCREAMING_SNAKE_CASE_   	=    use_labels
											SCREAMING_SNAKE_CASE_   	=    is_training
											SCREAMING_SNAKE_CASE_   	=    num_labels
											SCREAMING_SNAKE_CASE_   	=    initializer_range
											SCREAMING_SNAKE_CASE_   	=    scope
											SCREAMING_SNAKE_CASE_   	=    width_multiplier
											SCREAMING_SNAKE_CASE_   	=    ffn_dropout
											SCREAMING_SNAKE_CASE_   	=    attn_dropout


				def     _A							(							self:   Tuple		):
											SCREAMING_SNAKE_CASE_   	=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    None
											if self.use_labels:
																		SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.batch_size]		,					self.num_labels		)
																		SCREAMING_SNAKE_CASE_   	=    ids_tensor([self.batch_size, self.image_size, self.image_size]		,					self.num_labels		)

											SCREAMING_SNAKE_CASE_   	=    self.get_config()

											return config, pixel_values, labels, pixel_labels


				def     _A							(							self:   List[str]		):
											return MobileViTVaConfig(
											    image_size=self.image_size		,					patch_size=self.patch_size		,					num_channels=self.num_channels		,					hidden_act=self.hidden_act		,					conv_kernel_size=self.conv_kernel_size		,					output_stride=self.output_stride		,					classifier_dropout_prob=self.classifier_dropout_prob		,					initializer_range=self.initializer_range		,					width_multiplier=self.width_multiplier		,					ffn_dropout=self.ffn_dropout_prob		,					attn_dropout=self.attn_dropout_prob		,					)


				def     _A							(							self:   int		,					_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   str		,					_lowerCamelCase:   List[Any]		,					_lowerCamelCase:   Union[str, Any]		):
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaModel(config=_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    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,
											    )		,					)


				def     _A							(							self:   int		,					_lowerCamelCase:   Tuple		,					_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   Dict		):
											SCREAMING_SNAKE_CASE_   	=    self.num_labels
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaForImageClassification(_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					labels=_lowerCamelCase		)
											self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_labels)		)


				def     _A							(							self:   Optional[Any]		,					_lowerCamelCase:   List[Any]		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   Dict		,					_lowerCamelCase:   List[str]		):
											SCREAMING_SNAKE_CASE_   	=    self.num_labels
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaForSemanticSegmentation(_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    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,
											    )		,					)
											SCREAMING_SNAKE_CASE_   	=    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     _A							(							self:   Optional[int]		):
											SCREAMING_SNAKE_CASE_   	=    self.prepare_config_and_inputs()
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    config_and_inputs
											SCREAMING_SNAKE_CASE_   	=    {'''pixel_values''': pixel_values}
											return config, inputs_dict






@require_torch
class  __magic_name__						(  __UpperCAmelCase    ,  __UpperCAmelCase    ,  unittest.TestCase):
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							Any	      =					(
				    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)

				SCREAMING_SNAKE_CASE__					:							Union[str, Any]	      =					(
				    {
				        "feature-extraction": MobileViTVaModel,
				        "image-classification": MobileViTVaForImageClassification,
				        "image-segmentation": MobileViTVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE__					:							Union[str, Any]	      =					False
				SCREAMING_SNAKE_CASE__					:							int	      =					False
				SCREAMING_SNAKE_CASE__					:							Tuple	      =					False
				SCREAMING_SNAKE_CASE__					:							Any	      =					False


				def     _A							(							self:   Tuple		):
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaModelTester(self		)
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaConfigTester(self		,					config_class=_lowerCamelCase		,					has_text_modality=_lowerCamelCase		)


				def     _A							(							self:   Any		):
											self.config_tester.run_common_tests()


				@unittest.skip(reason='''MobileViTV2 does not use inputs_embeds'''		)
				def     _A							(							self:   List[Any]		):
											pass


				@unittest.skip(reason='''MobileViTV2 does not support input and output embeddings'''		)
				def     _A							(							self:   Optional[Any]		):
											pass


				@unittest.skip(reason='''MobileViTV2 does not output attentions'''		)
				def     _A							(							self:   List[Any]		):
											pass


				@require_torch_multi_gpu
				@unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.'''		)
				def     _A							(							self:   Optional[Any]		):
											pass


				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''		)
				def     _A							(							self:   Any		):
											pass


				def     _A							(							self:   Any		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()

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

																		SCREAMING_SNAKE_CASE_   	=    ['''pixel_values''']
																		self.assertListEqual(arg_names[:1]		,					_lowerCamelCase		)


				def     _A							(							self:   Tuple		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCamelCase		)


				def     _A							(							self:   Optional[Any]		):
											def check_hidden_states_output(_lowerCamelCase:   Union[str, Any]		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Any		):
																		SCREAMING_SNAKE_CASE_   	=    model_class(_lowerCamelCase		)
																		model.to(_lowerCamelCase		)
																		model.eval()

																		with torch.no_grad():
																									SCREAMING_SNAKE_CASE_   	=    model(**self._prepare_for_class(_lowerCamelCase		,					_lowerCamelCase		)		)

																		SCREAMING_SNAKE_CASE_   	=    outputs.hidden_states

																		SCREAMING_SNAKE_CASE_   	=    5
																		self.assertEqual(len(_lowerCamelCase		)		,					_lowerCamelCase		)

																		# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
																		# with the width and height being successively divided by 2.
																		SCREAMING_SNAKE_CASE_   	=    2
																		for i in range(len(_lowerCamelCase		)		):
																									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		)

											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		SCREAMING_SNAKE_CASE_   	=    True
																		check_hidden_states_output(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		SCREAMING_SNAKE_CASE_   	=    True

																		check_hidden_states_output(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)


				def     _A							(							self:   str		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase		)


				def     _A							(							self:   Union[str, Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase		)





				@slow
				def     _A							(							self:   List[str]		):
											for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		SCREAMING_SNAKE_CASE_   	=    MobileViTVaModel.from_pretrained(_lowerCamelCase		)
																		self.assertIsNotNone(_lowerCamelCase		)






def 			a   ():
							SCREAMING_SNAKE_CASE_   	=    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
							return image






@require_torch
@require_vision
class  __magic_name__						(  unittest.TestCase):
				'''simple docstring'''







				@cached_property
				def     _A							(							self:   List[Any]		):
											return (
											    MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''		)
											    if is_vision_available()
											    else None
											)


				@slow
				def     _A							(							self:   List[Any]		):
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''		).to(
											    _lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    self.default_image_processor
											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=_lowerCamelCase		,					return_tensors='''pt'''		).to(_lowerCamelCase		)

											# forward pass
											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(**_lowerCamelCase		)

											# verify the logits
											SCREAMING_SNAKE_CASE_   	=    torch.Size((1, 10_00)		)
											self.assertEqual(outputs.logits.shape		,					_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]		).to(_lowerCamelCase		)

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


				@slow
				def     _A							(							self:   Optional[Any]		):
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)
											SCREAMING_SNAKE_CASE_   	=    model.to(_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)

											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=_lowerCamelCase		,					return_tensors='''pt'''		).to(_lowerCamelCase		)

											# forward pass
											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(**_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    outputs.logits

											# verify the logits
											SCREAMING_SNAKE_CASE_   	=    torch.Size((1, 21, 32, 32)		)
											self.assertEqual(logits.shape		,					_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    torch.tensor(
											    [
											        [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
											        [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
											        [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
											    ]		,					device=_lowerCamelCase		,					)

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





				@slow
				def     _A							(							self:   Any		):
											SCREAMING_SNAKE_CASE_   	=    MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)
											SCREAMING_SNAKE_CASE_   	=    model.to(_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)

											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=_lowerCamelCase		,					return_tensors='''pt'''		).to(_lowerCamelCase		)

											# forward pass
											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(**_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    outputs.logits.detach().cpu()

											SCREAMING_SNAKE_CASE_   	=    image_processor.post_process_semantic_segmentation(outputs=_lowerCamelCase		,					target_sizes=[(50, 60)]		)
											SCREAMING_SNAKE_CASE_   	=    torch.Size((50, 60)		)
											self.assertEqual(segmentation[0].shape		,					_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    image_processor.post_process_semantic_segmentation(outputs=_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    torch.Size((32, 32)		)
											self.assertEqual(segmentation[0].shape		,					_lowerCamelCase		)








def 			a   (_lowerCAmelCase     ):
							if number > 0:
														raise ValueError('''input must be a negative integer'''     )
							SCREAMING_SNAKE_CASE_   	=    len(bin(_lowerCAmelCase     )[3:]     )
							SCREAMING_SNAKE_CASE_   	=    bin(abs(_lowerCAmelCase     ) - (1 << binary_number_length)     )[3:]
							SCREAMING_SNAKE_CASE_   	=    (
							    (
							        '''1'''
							        + '''0''' * (binary_number_length - len(_lowerCAmelCase     ))
							        + twos_complement_number
							    )
							    if number < 0
							    else '''0'''
							)
							return "0b" + twos_complement_number


if __name__ == "__main__":
			import doctest

			doctest.testmod()


