



"""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       UpperCamelCase__   (	_UpperCAmelCase  ):




      """simple docstring"""




      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				str								= self.config_class(**self.inputs_dict       )
        self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_    ,			'width_multiplier'       )       )







class       UpperCamelCase__   :




      """simple docstring"""




      def __init__(      self				:      Any    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]=1_3    ,			SCREAMING_SNAKE_CASE_				:      Tuple=6_4    ,			SCREAMING_SNAKE_CASE_				:      int=2    ,			SCREAMING_SNAKE_CASE_				:      Dict=3    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]="swish"    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=3    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=3_2    ,			SCREAMING_SNAKE_CASE_				:      List[str]=0.1    ,			SCREAMING_SNAKE_CASE_				:      Any=0.02    ,			SCREAMING_SNAKE_CASE_				:      Optional[int]=True    ,			SCREAMING_SNAKE_CASE_				:      Any=True    ,			SCREAMING_SNAKE_CASE_				:      str=1_0    ,			SCREAMING_SNAKE_CASE_				:      Tuple=None    ,			SCREAMING_SNAKE_CASE_				:      int=0.25    ,			SCREAMING_SNAKE_CASE_				:      Tuple=0.0    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]=0.0    ,			):
        lowerCAmelCase_   :				Optional[Any]								= parent
        lowerCAmelCase_   :				int								= batch_size
        lowerCAmelCase_   :				Optional[int]								= image_size
        lowerCAmelCase_   :				int								= patch_size
        lowerCAmelCase_   :				List[str]								= num_channels
        lowerCAmelCase_   :				Any								= make_divisible(5_1_2 * width_multiplier    ,			divisor=8       )
        lowerCAmelCase_   :				int								= hidden_act
        lowerCAmelCase_   :				str								= conv_kernel_size
        lowerCAmelCase_   :				Union[str, Any]								= output_stride
        lowerCAmelCase_   :				Optional[Any]								= classifier_dropout_prob
        lowerCAmelCase_   :				Any								= use_labels
        lowerCAmelCase_   :				Tuple								= is_training
        lowerCAmelCase_   :				List[Any]								= num_labels
        lowerCAmelCase_   :				Optional[int]								= initializer_range
        lowerCAmelCase_   :				Any								= scope
        lowerCAmelCase_   :				Tuple								= width_multiplier
        lowerCAmelCase_   :				Dict								= ffn_dropout
        lowerCAmelCase_   :				Any								= attn_dropout



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_   :				int								= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

        lowerCAmelCase_   :				Tuple								= None
        lowerCAmelCase_   :				int								= None
        if self.use_labels:
          lowerCAmelCase_   :				Optional[Any]								= ids_tensor([self.batch_size]    ,			self.num_labels       )
          lowerCAmelCase_   :				Any								= ids_tensor([self.batch_size, self.image_size, self.image_size]    ,			self.num_labels       )

        lowerCAmelCase_   :				List[Any]								= self.get_config()

        return config, pixel_values, labels, pixel_labels



      def      SCREAMING_SNAKE_CASE__ (      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      SCREAMING_SNAKE_CASE__ (      self				:      List[str]    ,			SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      Any       ):
        lowerCAmelCase_   :				Optional[Any]								= MobileViTVaModel(config=SCREAMING_SNAKE_CASE_       )
        model.to(SCREAMING_SNAKE_CASE_       )
        model.eval()
        lowerCAmelCase_   :				Any								= model(SCREAMING_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      SCREAMING_SNAKE_CASE__ (      self				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      Optional[Any]    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      Union[str, Any]    ,			SCREAMING_SNAKE_CASE_				:      str       ):
        lowerCAmelCase_   :				List[str]								= self.num_labels
        lowerCAmelCase_   :				Dict								= MobileViTVaForImageClassification(SCREAMING_SNAKE_CASE_       )
        model.to(SCREAMING_SNAKE_CASE_       )
        model.eval()
        lowerCAmelCase_   :				int								= model(SCREAMING_SNAKE_CASE_    ,			labels=SCREAMING_SNAKE_CASE_       )
        self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)       )



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







@require_torch
class       UpperCamelCase__   (	_UpperCAmelCase,					_UpperCAmelCase,					unittest.TestCase  ):




      """simple docstring"""




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

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

      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False
      _SCREAMING_SNAKE_CASE  				=     False



      def      SCREAMING_SNAKE_CASE__ (      self				:      Dict       ):
        lowerCAmelCase_   :				Union[str, Any]								= MobileViTVaModelTester(self       )
        lowerCAmelCase_   :				str								= MobileViTVaConfigTester(self    ,			config_class=SCREAMING_SNAKE_CASE_    ,			has_text_modality=SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        self.config_tester.run_common_tests()



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



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



      @unittest.skip(reason='MobileViTV2 does not output attentions'       )
      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        pass



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



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



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        lowerCAmelCase_						,lowerCAmelCase_   :				List[str]								= self.model_tester.prepare_config_and_inputs_for_common()

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

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



      def      SCREAMING_SNAKE_CASE__ (      self				:      Dict       ):
        lowerCAmelCase_   :				List[Any]								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:      Dict    ,			SCREAMING_SNAKE_CASE_				:      List[Any]    ,			SCREAMING_SNAKE_CASE_				:      List[str]       ):
          lowerCAmelCase_   :				int								= model_class(SCREAMING_SNAKE_CASE_       )
          model.to(SCREAMING_SNAKE_CASE_       )
          model.eval()

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

          lowerCAmelCase_   :				Union[str, Any]								= outputs.hidden_states

          lowerCAmelCase_   :				Tuple								= 5
          self.assertEqual(len(SCREAMING_SNAKE_CASE_       )    ,			SCREAMING_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.
          lowerCAmelCase_   :				Optional[int]								= 2
          for i in range(len(SCREAMING_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[int]								= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          lowerCAmelCase_   :				List[str]								= True
          check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )

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

          check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_    ,			SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        lowerCAmelCase_   :				Tuple								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_       )



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        lowerCAmelCase_   :				Union[str, Any]								= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_       )





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_   :				Tuple								= MobileViTVaModel.from_pretrained(SCREAMING_SNAKE_CASE_       )
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_       )




def 				UpperCamelCase_    (    )						->   Any:

  """simple docstring"""




  lowerCAmelCase_   :				Union[str, Any]								= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  return image







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




      """simple docstring"""




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



      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				Any								= MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'       ).to(
            SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[Any]								= self.default_image_processor
        lowerCAmelCase_   :				Tuple								= prepare_img()
        lowerCAmelCase_   :				List[Any]								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='pt'       ).to(SCREAMING_SNAKE_CASE_       )

        # forward pass
        with torch.no_grad():
          lowerCAmelCase_   :				Optional[Any]								= model(**SCREAMING_SNAKE_CASE_       )

        # verify the logits
        lowerCAmelCase_   :				Any								= torch.Size((1, 1_0_0_0)       )
        self.assertEqual(outputs.logits.shape    ,			SCREAMING_SNAKE_CASE_       )

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

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



      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        lowerCAmelCase_   :				Any								= MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )
        lowerCAmelCase_   :				int								= model.to(SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				int								= MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )

        lowerCAmelCase_   :				str								= prepare_img()
        lowerCAmelCase_   :				Any								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='pt'       ).to(SCREAMING_SNAKE_CASE_       )

        # forward pass
        with torch.no_grad():
          lowerCAmelCase_   :				List[Any]								= model(**SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				int								= outputs.logits

        # verify the logits
        lowerCAmelCase_   :				Any								= torch.Size((1, 2_1, 3_2, 3_2)       )
        self.assertEqual(logits.shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[Any]								= 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=SCREAMING_SNAKE_CASE_    ,			)

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





      @slow
      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        lowerCAmelCase_   :				Optional[int]								= MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )
        lowerCAmelCase_   :				str								= model.to(SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				List[str]								= MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'       )

        lowerCAmelCase_   :				Dict								= prepare_img()
        lowerCAmelCase_   :				List[Any]								= image_processor(images=SCREAMING_SNAKE_CASE_    ,			return_tensors='pt'       ).to(SCREAMING_SNAKE_CASE_       )

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

        lowerCAmelCase_   :				Dict								= outputs.logits.detach().cpu()

        lowerCAmelCase_   :				List[Any]								= image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_    ,			target_sizes=[(5_0, 6_0)]       )
        lowerCAmelCase_   :				Dict								= torch.Size((5_0, 6_0)       )
        self.assertEqual(segmentation[0].shape    ,			SCREAMING_SNAKE_CASE_       )

        lowerCAmelCase_   :				Optional[Any]								= image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_       )
        lowerCAmelCase_   :				Union[str, Any]								= torch.Size((3_2, 3_2)       )
        self.assertEqual(segmentation[0].shape    ,			SCREAMING_SNAKE_CASE_       )












"""simple docstring"""





def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						int							,						SCREAMING_SNAKE_CASE     :						int			):







      '''simple docstring'''




      while b:
            lowerCAmelCase						,		lowerCAmelCase  						=       b, a % b
      return a


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						int							,						SCREAMING_SNAKE_CASE     :						int			):







      '''simple docstring'''




      return a if b == 0 else euclidean_gcd_recursive(SCREAMING_SNAKE_CASE							,						a % b			)


def 			UpperCAmelCase__							(  ):







      '''simple docstring'''




      print(F'euclidean_gcd(3, 5) = {euclidean_gcd(3							,						5			)}'			)
      print(F'euclidean_gcd(5, 3) = {euclidean_gcd(5							,						3			)}'			)
      print(F'euclidean_gcd(1, 3) = {euclidean_gcd(1							,						3			)}'			)
      print(F'euclidean_gcd(3, 6) = {euclidean_gcd(3							,						6			)}'			)
      print(F'euclidean_gcd(6, 3) = {euclidean_gcd(6							,						3			)}'			)

      print(F'euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3							,						5			)}'			)
      print(F'euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5							,						3			)}'			)
      print(F'euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1							,						3			)}'			)
      print(F'euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3							,						6			)}'			)
      print(F'euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6							,						3			)}'			)


if __name__ == "__main__":
       main()






