


'''simple docstring'''





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 						a__					(					a_   ):





			'''simple docstring'''

			def 					lowerCAmelCase     (  self							:			Tuple	)      ->		Any:
						__A=	self.config_class(**self.inputs_dict	)
						self.parent.assertTrue(hasattr(lowerCAmelCase_			,    'width_multiplier'	)	)


class 						a__					:





			'''simple docstring'''

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

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

						__A=	self.get_config()

						return config, pixel_values, labels, pixel_labels
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		List[Any]:
						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 					lowerCAmelCase     (  self							:			Tuple			,    lowerCAmelCase_							:			List[Any]			,    lowerCAmelCase_							:			Dict			,    lowerCAmelCase_							:			str			,    lowerCAmelCase_							:			Dict	)      ->		List[str]:
						__A=	MobileViTVaModel(config=lowerCAmelCase_	)
						model.to(lowerCAmelCase_	)
						model.eval()
						__A=	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 					lowerCAmelCase     (  self							:			Union[str, Any]			,    lowerCAmelCase_							:			List[Any]			,    lowerCAmelCase_							:			Tuple			,    lowerCAmelCase_							:			int			,    lowerCAmelCase_							:			Dict	)      ->		Optional[int]:
						__A=	self.num_labels
						__A=	MobileViTVaForImageClassification(lowerCAmelCase_	)
						model.to(lowerCAmelCase_	)
						model.eval()
						__A=	model(lowerCAmelCase_			,    labels=lowerCAmelCase_	)
						self.parent.assertEqual(result.logits.shape			,    (self.batch_size, self.num_labels)	)
			def 					lowerCAmelCase     (  self							:			Dict			,    lowerCAmelCase_							:			int			,    lowerCAmelCase_							:			List[Any]			,    lowerCAmelCase_							:			int			,    lowerCAmelCase_							:			str	)      ->		Tuple:
						__A=	self.num_labels
						__A=	MobileViTVaForSemanticSegmentation(lowerCAmelCase_	)
						model.to(lowerCAmelCase_	)
						model.eval()
						__A=	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,
						    )			,    )
						__A=	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							:			Tuple	)      ->		Optional[int]:
						__A=	self.prepare_config_and_inputs()
						__A,	__A,	__A,	__A=	config_and_inputs
						__A=	{'pixel_values': pixel_values}
						return config, inputs_dict


@require_torch
class 						a__					(					a_      ,  a_      ,  unittest.TestCase   ):





			'''simple docstring'''

			A						:				Optional[Any]					      =			(
			    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)

			A						:				str					      =			(
			    {
			        '''feature-extraction''': MobileViTVaModel,
			        '''image-classification''': MobileViTVaForImageClassification,
			        '''image-segmentation''': MobileViTVaForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			A						:				int					      =			False
			A						:				Any					      =			False
			A						:				int					      =			False
			A						:				Optional[int]					      =			False
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		Any:
						__A=	MobileViTVaModelTester(self	)
						__A=	MobileViTVaConfigTester(self			,    config_class=lowerCAmelCase_			,    has_text_modality=lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			str	)      ->		Union[str, Any]:
						self.config_tester.run_common_tests()
			@unittest.skip(reason='MobileViTV2 does not use inputs_embeds'	)
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		str:
						pass
			@unittest.skip(reason='MobileViTV2 does not support input and output embeddings'	)
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		str:
						pass
			@unittest.skip(reason='MobileViTV2 does not output attentions'	)
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Dict:
						pass
			@require_torch_multi_gpu
			@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'	)
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Any:
						pass
			@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'	)
			def 					lowerCAmelCase     (  self							:			int	)      ->		List[str]:
						pass
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		int:
						__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()

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

									__A=	['pixel_values']
									self.assertListEqual(arg_names[:1]			,    lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Union[str, Any]	)      ->		Tuple:
						__A=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			List[str]	)      ->		Tuple:
						def check_hidden_states_output(lowerCAmelCase_							:			Optional[Any]			,    lowerCAmelCase_							:			List[str]			,    lowerCAmelCase_							:			List[Any]	):
									__A=	model_class(lowerCAmelCase_	)
									model.to(lowerCAmelCase_	)
									model.eval()

									with torch.no_grad():
												__A=	model(**self._prepare_for_class(lowerCAmelCase_			,    lowerCAmelCase_	)	)

									__A=	outputs.hidden_states

									__A=	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.
									__A=	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	)

						__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									__A=	True
									check_hidden_states_output(lowerCAmelCase_			,    lowerCAmelCase_			,    lowerCAmelCase_	)

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

									check_hidden_states_output(lowerCAmelCase_			,    lowerCAmelCase_			,    lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		int:
						__A=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Any	)      ->		Any:
						__A=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase_	)

			@slow
			def 					lowerCAmelCase     (  self							:			List[str]	)      ->		Union[str, Any]:
						for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__A=	MobileViTVaModel.from_pretrained(lowerCAmelCase_	)
									self.assertIsNotNone(lowerCAmelCase_	)






def 						UpperCAmelCase__(				):






			"""simple docstring"""




			__A=	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							:			Dict	)      ->		List[str]:
						return (
						    MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'	)
						    if is_vision_available()
						    else None
						)
			@slow
			def 					lowerCAmelCase     (  self							:			List[str]	)      ->		str:
						__A=	MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'	).to(
						    lowerCAmelCase_	)

						__A=	self.default_image_processor
						__A=	prepare_img()
						__A=	image_processor(images=lowerCAmelCase_			,    return_tensors='pt'	).to(lowerCAmelCase_	)

						# forward pass
						with torch.no_grad():
									__A=	model(**lowerCAmelCase_	)

						# verify the logits
						__A=	torch.Size((1, 1_000)	)
						self.assertEqual(outputs.logits.shape			,    lowerCAmelCase_	)

						__A=	torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01]	).to(lowerCAmelCase_	)

						self.assertTrue(torch.allclose(outputs.logits[0, :3]			,    lowerCAmelCase_			,    atol=1E-4	)	)
			@slow
			def 					lowerCAmelCase     (  self							:			Any	)      ->		List[Any]:
						__A=	MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'	)
						__A=	model.to(lowerCAmelCase_	)

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

						__A=	prepare_img()
						__A=	image_processor(images=lowerCAmelCase_			,    return_tensors='pt'	).to(lowerCAmelCase_	)

						# forward pass
						with torch.no_grad():
									__A=	model(**lowerCAmelCase_	)
						__A=	outputs.logits

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

						__A=	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 					lowerCAmelCase     (  self							:			Union[str, Any]	)      ->		List[Any]:
						__A=	MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'	)
						__A=	model.to(lowerCAmelCase_	)

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

						__A=	prepare_img()
						__A=	image_processor(images=lowerCAmelCase_			,    return_tensors='pt'	).to(lowerCAmelCase_	)

						# forward pass
						with torch.no_grad():
									__A=	model(**lowerCAmelCase_	)

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

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

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







'''simple docstring'''





import math






def 						UpperCAmelCase__(				_SCREAMING_SNAKE_CASE					: int ):






			"""simple docstring"""




			if not isinstance(_SCREAMING_SNAKE_CASE,_SCREAMING_SNAKE_CASE ):
						__A=	f"""Input value of [number={number}] must be an integer"""
						raise TypeError(_SCREAMING_SNAKE_CASE )

			if number < 1:
						__A=	f"""Input value of [number={number}] must be > 0"""
						raise ValueError(_SCREAMING_SNAKE_CASE )
			elif number == 1:
						return 3
			elif number == 2:
						return 5
			else:
						__A=	int(math.log(number // 3,2 ) ) + 2

						__A=	[3, 5]
						__A=	2
						__A=	3
						for block in range(1,_SCREAMING_SNAKE_CASE ):
									for _ in range(_SCREAMING_SNAKE_CASE ):
												proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] )
												proth_index += 1
									increment *= 2

			return proth_list[number - 1]


if __name__ == "__main__":
					import doctest

					doctest.testmod()

					for number in range(1_1):
										UpperCAmelCase__  			=				0
										try:
															UpperCAmelCase__  			=				proth(number)
										except ValueError:
															print(F"""ValueError: there is no {number}th Proth number""")
															continue

										print(F"""The {number}th Proth number: {value}""")



