



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       _lowercase   (a_      ):
				'''simple docstring'''







				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.config_class(**self.inputs_dict    )
									self.parent.assertTrue(hasattr(snake_case__     , "width_multiplier"    )    )




class       _lowercase   :
				'''simple docstring'''







				def __init__( self     , snake_case__     , snake_case__=13     , snake_case__=64     , snake_case__=2     , snake_case__=3     , snake_case__="swish"     , snake_case__=3     , snake_case__=32     , snake_case__=0.1     , snake_case__=0.02     , snake_case__=True     , snake_case__=True     , snake_case__=10     , snake_case__=None     , snake_case__=0.25     , snake_case__=0.0     , snake_case__=0.0     , ):

									'''simple docstring'''


									UpperCamelCase_		  =   parent
									UpperCamelCase_		  =   batch_size
									UpperCamelCase_		  =   image_size
									UpperCamelCase_		  =   patch_size
									UpperCamelCase_		  =   num_channels
									UpperCamelCase_		  =   make_divisible(512 * width_multiplier     , divisor=8    )
									UpperCamelCase_		  =   hidden_act
									UpperCamelCase_		  =   conv_kernel_size
									UpperCamelCase_		  =   output_stride
									UpperCamelCase_		  =   classifier_dropout_prob
									UpperCamelCase_		  =   use_labels
									UpperCamelCase_		  =   is_training
									UpperCamelCase_		  =   num_labels
									UpperCamelCase_		  =   initializer_range
									UpperCamelCase_		  =   scope
									UpperCamelCase_		  =   width_multiplier
									UpperCamelCase_		  =   ffn_dropout
									UpperCamelCase_		  =   attn_dropout

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

									UpperCamelCase_		  =   self.get_config()

									return config, pixel_values, labels, pixel_labels

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


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

									'''simple docstring'''


									UpperCamelCase_		  =   MobileViTVaModel(config=snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   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       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__     , snake_case__    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.num_labels
									UpperCamelCase_		  =   MobileViTVaForImageClassification(snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   model(snake_case__     , labels=snake_case__    )
									self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)    )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__     , snake_case__    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.num_labels
									UpperCamelCase_		  =   MobileViTVaForSemanticSegmentation(snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   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,
									    )     , )
									UpperCamelCase_		  =   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       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.prepare_config_and_inputs()
									UpperCamelCase_  ,    UpperCamelCase_  ,    UpperCamelCase_  ,    UpperCamelCase_		  =   config_and_inputs
									UpperCamelCase_		  =   {"pixel_values": pixel_values}
									return config, inputs_dict




@require_torch
class       _lowercase   (a_      ,   a_      ,   unittest.TestCase      ):
				'''simple docstring'''







				lowercase__   						=						(
				    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)

				lowercase__   						=						(
				    {
				        """feature-extraction""": MobileViTVaModel,
				        """image-classification""": MobileViTVaForImageClassification,
				        """image-segmentation""": MobileViTVaForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				lowercase__   						=						False
				lowercase__   						=						False
				lowercase__   						=						False
				lowercase__   						=						False

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   MobileViTVaModelTester(self    )
									UpperCamelCase_		  =   MobileViTVaConfigTester(self     , config_class=snake_case__     , has_text_modality=snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									self.config_tester.run_common_tests()

				@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				@unittest.skip(reason="MobileViTV2 does not output attentions"    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				@require_torch_multi_gpu
				@unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_  ,    UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs_for_common()

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

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

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									def check_hidden_states_output(snake_case__     , snake_case__     , snake_case__    ):
														UpperCamelCase_		  =   model_class(snake_case__    )
														model.to(snake_case__    )
														model.eval()

														with torch.no_grad():
																			UpperCamelCase_		  =   model(**self._prepare_for_class(snake_case__     , snake_case__    )    )

														UpperCamelCase_		  =   outputs.hidden_states

														UpperCamelCase_		  =   5
														self.assertEqual(len(snake_case__    )     , snake_case__    )

														# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
														# with the width and height being successively divided by 2.
														UpperCamelCase_		  =   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    )

									UpperCamelCase_  ,    UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
														UpperCamelCase_		  =   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"]
														UpperCamelCase_		  =   True

														check_hidden_states_output(snake_case__     , snake_case__     , snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__    )

				@slow
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														UpperCamelCase_		  =   MobileViTVaModel.from_pretrained(snake_case__    )
														self.assertIsNotNone(snake_case__    )




def    _lowerCAmelCase    ():
					UpperCamelCase_		  =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
					return image






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







				@cached_property
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									return (
									    MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"    )
									    if is_vision_available()
									    else None
									)

				@slow
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"    ).to(
									    snake_case__    )

									UpperCamelCase_		  =   self.default_image_processor
									UpperCamelCase_		  =   prepare_img()
									UpperCamelCase_		  =   image_processor(images=snake_case__     , return_tensors="pt"    ).to(snake_case__    )

									# forward pass
									with torch.no_grad():
														UpperCamelCase_		  =   model(**snake_case__    )

									# verify the logits
									UpperCamelCase_		  =   torch.Size((1, 1000)    )
									self.assertEqual(outputs.logits.shape     , snake_case__    )

									UpperCamelCase_		  =   torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01]    ).to(snake_case__    )

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

				@slow
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )
									UpperCamelCase_		  =   model.to(snake_case__    )

									UpperCamelCase_		  =   MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )

									UpperCamelCase_		  =   prepare_img()
									UpperCamelCase_		  =   image_processor(images=snake_case__     , return_tensors="pt"    ).to(snake_case__    )

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

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

									UpperCamelCase_		  =   torch.tensor(
									    [
									        [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
									        [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
									        [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
									    ]     , device=snake_case__     , )

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

				@slow
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )
									UpperCamelCase_		  =   model.to(snake_case__    )

									UpperCamelCase_		  =   MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )

									UpperCamelCase_		  =   prepare_img()
									UpperCamelCase_		  =   image_processor(images=snake_case__     , return_tensors="pt"    ).to(snake_case__    )

									# forward pass
									with torch.no_grad():
														UpperCamelCase_		  =   model(**snake_case__    )

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

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

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





from decimal import Decimal, getcontext
from math import ceil, factorial



def    _lowerCAmelCase    (_lowerCAmelCase):

					if not isinstance(_lowerCAmelCase   ,	_lowerCAmelCase):
										raise TypeError("Undefined for non-integers")
					elif precision < 1:
										raise ValueError("Undefined for non-natural numbers")

					UpperCamelCase_		  =   precision
					UpperCamelCase_		  =   ceil(precision / 14)
					UpperCamelCase_		  =   42_68_80 * Decimal(1_00_05).sqrt()
					UpperCamelCase_		  =   1
					UpperCamelCase_		  =   13_59_14_09
					UpperCamelCase_		  =   Decimal(_lowerCAmelCase)
					for k in range(1   ,	_lowerCAmelCase):
										UpperCamelCase_		  =   factorial(6 * k) // (factorial(3 * k) * factorial(_lowerCAmelCase) ** 3)
										linear_term += 5_45_14_01_34
										exponential_term *= -26_25_37_41_26_40_76_80_00
										partial_sum += Decimal(multinomial_term * linear_term) / exponential_term
					return str(constant_term / partial_sum)[:-1]


if __name__ == "__main__":
	UpperCAmelCase   :							Any							 =50
	print(F"The first {n} digits of pi is: {pi(n)}")
