


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					(	__A	):





      def 							_lowercase					(		self    :       Optional[Any]							)     -> Tuple:






         """simple docstring"""







         UpperCAmelCase      					=  self.config_class(**self.inputs_dict							)
         self.parent.assertTrue(hasattr(__lowerCamelCase       ,							"""hidden_sizes"""							)							)
         self.parent.assertTrue(hasattr(__lowerCamelCase       ,							"""neck_hidden_sizes"""							)							)
         self.parent.assertTrue(hasattr(__lowerCamelCase       ,							"""num_attention_heads"""							)							)






class 	__lowercase					:





      def __init__(		self    :       str       ,							__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       Optional[int]=1_3       ,							__lowerCamelCase    :       Union[str, Any]=3_2       ,							__lowerCamelCase    :       Tuple=2       ,							__lowerCamelCase    :       List[str]=3       ,							__lowerCamelCase    :       List[str]=6_4_0       ,							__lowerCamelCase    :       Optional[Any]=4       ,							__lowerCamelCase    :       List[Any]="silu"       ,							__lowerCamelCase    :       Union[str, Any]=3       ,							__lowerCamelCase    :       Union[str, Any]=3_2       ,							__lowerCamelCase    :       Dict=0.1       ,							__lowerCamelCase    :       Tuple=0.1       ,							__lowerCamelCase    :       str=0.1       ,							__lowerCamelCase    :       Dict=0.02       ,							__lowerCamelCase    :       List[Any]=True       ,							__lowerCamelCase    :       Optional[int]=True       ,							__lowerCamelCase    :       Any=1_0       ,							__lowerCamelCase    :       Optional[int]=None       ,							)     -> str:






         """simple docstring"""







         UpperCAmelCase      					=  parent
         UpperCAmelCase      					=  batch_size
         UpperCAmelCase      					=  image_size
         UpperCAmelCase      					=  patch_size
         UpperCAmelCase      					=  num_channels
         UpperCAmelCase      					=  last_hidden_size
         UpperCAmelCase      					=  num_attention_heads
         UpperCAmelCase      					=  hidden_act
         UpperCAmelCase      					=  conv_kernel_size
         UpperCAmelCase      					=  output_stride
         UpperCAmelCase      					=  hidden_dropout_prob
         UpperCAmelCase      					=  attention_probs_dropout_prob
         UpperCAmelCase      					=  classifier_dropout_prob
         UpperCAmelCase      					=  use_labels
         UpperCAmelCase      					=  is_training
         UpperCAmelCase      					=  num_labels
         UpperCAmelCase      					=  initializer_range
         UpperCAmelCase      					=  scope





      def 							_lowercase					(		self    :       Optional[int]							)     -> List[Any]:






         """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 							_lowercase					(		self    :       str							)     -> Optional[int]:






         """simple docstring"""







         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 							_lowercase					(		self    :       str       ,							__lowerCamelCase    :       str       ,							__lowerCamelCase    :       Optional[int]       ,							__lowerCamelCase    :       Union[str, Any]       ,							__lowerCamelCase    :       Optional[int]							)     -> Union[str, Any]:






         """simple docstring"""







         UpperCAmelCase      					=  MobileViTModel(config=__lowerCamelCase							)
         model.to(__lowerCamelCase							)
         model.eval()
         UpperCAmelCase      					=  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 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Optional[Any]       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       Union[str, Any]       ,							__lowerCamelCase    :       Optional[int]							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  self.num_labels
         UpperCAmelCase      					=  MobileViTForImageClassification(__lowerCamelCase							)
         model.to(__lowerCamelCase							)
         model.eval()
         UpperCAmelCase      					=  model(__lowerCamelCase       ,							labels=__lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_labels)							)





      def 							_lowercase					(		self    :       Optional[int]       ,							__lowerCamelCase    :       Optional[int]       ,							__lowerCamelCase    :       Union[str, Any]       ,							__lowerCamelCase    :       int       ,							__lowerCamelCase    :       Dict							)     -> str:






         """simple docstring"""







         UpperCAmelCase      					=  self.num_labels
         UpperCAmelCase      					=  MobileViTForSemanticSegmentation(__lowerCamelCase							)
         model.to(__lowerCamelCase							)
         model.eval()
         UpperCAmelCase      					=  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,
             )       ,							)
         UpperCAmelCase      					=  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 							_lowercase					(		self    :       Optional[Any]							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  self.prepare_config_and_inputs()
         UpperCAmelCase      					=  config_and_inputs
         UpperCAmelCase      					=  {'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_torch
class 	__lowercase					(	__A			,       __A			,       unittest.TestCase	):
      UpperCamelCase										=							(
          (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
          if is_torch_available()
          else ()
      )
      UpperCamelCase										=							(
          {
              '''feature-extraction''': MobileViTModel,
              '''image-classification''': MobileViTForImageClassification,
              '''image-segmentation''': MobileViTForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False





      def 							_lowercase					(		self    :       List[str]							)     -> Optional[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  MobileViTModelTester(self							)
         UpperCAmelCase      					=  MobileViTConfigTester(self       ,							config_class=__lowerCamelCase       ,							has_text_modality=__lowerCamelCase							)





      def 							_lowercase					(		self    :       Tuple							)     -> Tuple:






         """simple docstring"""







         self.config_tester.run_common_tests()





      @unittest.skip(reason="""MobileViT does not use inputs_embeds"""							)
      def 							_lowercase					(		self    :       Tuple							)     -> Optional[int]:






         """simple docstring"""







         pass





      @unittest.skip(reason="""MobileViT does not support input and output embeddings"""							)
      def 							_lowercase					(		self    :       str							)     -> int:






         """simple docstring"""







         pass





      @unittest.skip(reason="""MobileViT does not output attentions"""							)
      def 							_lowercase					(		self    :       List[str]							)     -> Optional[int]:






         """simple docstring"""







         pass





      def 							_lowercase					(		self    :       Optional[Any]							)     -> Optional[int]:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            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]       ,							__lowerCamelCase							)





      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""							)
      def 							_lowercase					(		self    :       str							)     -> Union[str, Any]:






         """simple docstring"""







         pass





      def 							_lowercase					(		self    :       Dict							)     -> Tuple:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase							)





      def 							_lowercase					(		self    :       Tuple							)     -> int:






         """simple docstring"""







         def check_hidden_states_output(__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       List[str]       ,							__lowerCamelCase    :       Optional[Any]							):
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()

            with torch.no_grad():
               UpperCAmelCase      					=  model(**self._prepare_for_class(__lowerCamelCase       ,							__lowerCamelCase							)							)

            UpperCAmelCase      					=  outputs.hidden_states

            UpperCAmelCase      					=  5
            self.assertEqual(len(__lowerCamelCase							)       ,							__lowerCamelCase							)

            # MobileViT'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(__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							)

         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase      					=  True
            check_hidden_states_output(__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase							)

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

            check_hidden_states_output(__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase							)





      def 							_lowercase					(		self    :       List[Any]							)     -> Union[str, Any]:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase							)





      def 							_lowercase					(		self    :       List[Any]							)     -> Any:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase							)





      @slow
      def 							_lowercase					(		self    :       List[str]							)     -> Optional[int]:






         """simple docstring"""







         for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCAmelCase      					=  MobileViTModel.from_pretrained(__lowerCamelCase							)
            self.assertIsNotNone(__lowerCamelCase							)

def 	_UpperCamelCase					(    )    ->Optional[Any]:
   UpperCAmelCase      					=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
   return image







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





      @cached_property
      def 							_lowercase					(		self    :       Dict							)     -> Optional[int]:






         """simple docstring"""







         return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""							) if is_vision_available() else None





      @slow
      def 							_lowercase					(		self    :       int							)     -> Dict:






         """simple docstring"""







         UpperCAmelCase      					=  MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""							).to(__lowerCamelCase							)

         UpperCAmelCase      					=  self.default_image_processor
         UpperCAmelCase      					=  prepare_img()
         UpperCAmelCase      					=  image_processor(images=__lowerCamelCase       ,							return_tensors="""pt"""							).to(__lowerCamelCase							)

         # forward pass
         with torch.no_grad():
            UpperCAmelCase      					=  model(**__lowerCamelCase							)

         # verify the logits
         UpperCAmelCase      					=  torch.Size((1, 1_0_0_0)							)
         self.assertEqual(outputs.logits.shape       ,							__lowerCamelCase							)

         UpperCAmelCase      					=  torch.tensor([-1.9_364, -1.2_327, -0.4_653]							).to(__lowerCamelCase							)

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





      @slow
      def 							_lowercase					(		self    :       Any							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)
         UpperCAmelCase      					=  model.to(__lowerCamelCase							)

         UpperCAmelCase      					=  MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)

         UpperCAmelCase      					=  prepare_img()
         UpperCAmelCase      					=  image_processor(images=__lowerCamelCase       ,							return_tensors="""pt"""							).to(__lowerCamelCase							)

         # forward pass
         with torch.no_grad():
            UpperCAmelCase      					=  model(**__lowerCamelCase							)
         UpperCAmelCase      					=  outputs.logits

         # verify the logits
         UpperCAmelCase      					=  torch.Size((1, 2_1, 3_2, 3_2)							)
         self.assertEqual(logits.shape       ,							__lowerCamelCase							)

         UpperCAmelCase      					=  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]],
                 [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_868, -9.7_132], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
                 [[-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=__lowerCamelCase       ,							)

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





      @slow
      def 							_lowercase					(		self    :       Optional[Any]							)     -> Union[str, Any]:






         """simple docstring"""







         UpperCAmelCase      					=  MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)
         UpperCAmelCase      					=  model.to(__lowerCamelCase							)

         UpperCAmelCase      					=  MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)

         UpperCAmelCase      					=  prepare_img()
         UpperCAmelCase      					=  image_processor(images=__lowerCamelCase       ,							return_tensors="""pt"""							).to(__lowerCamelCase							)

         # forward pass
         with torch.no_grad():
            UpperCAmelCase      					=  model(**__lowerCamelCase							)

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

         UpperCAmelCase      					=  image_processor.post_process_semantic_segmentation(outputs=__lowerCamelCase       ,							target_sizes=[(5_0, 6_0)]							)
         UpperCAmelCase      					=  torch.Size((5_0, 6_0)							)
         self.assertEqual(segmentation[0].shape       ,							__lowerCamelCase							)

         UpperCAmelCase      					=  image_processor.post_process_semantic_segmentation(outputs=__lowerCamelCase							)
         UpperCAmelCase      					=  torch.Size((3_2, 3_2)							)
         self.assertEqual(segmentation[0].shape       ,							__lowerCamelCase							)











'''simple docstring'''



import unittest
from dataclasses import dataclass

import pytest

from accelerate.commands.config.config_args import SageMakerConfig
from accelerate.utils import ComputeEnvironment
from accelerate.utils.launch import _convert_nargs_to_dict
@dataclass
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      ComputeEnvironment.AMAZON_SAGEMAKER
      UpperCamelCase_             =      True
      UpperCamelCase_             =      '''ml.p3.2xlarge'''
      UpperCamelCase_             =      '''accelerate_sagemaker_execution_role'''
      UpperCamelCase_             =      '''hf-sm'''
      UpperCamelCase_             =      '''us-east-1'''
      UpperCamelCase_             =      1
      UpperCamelCase_             =      '''accelerate-sagemaker-1'''
      UpperCamelCase_             =      '''1.6'''
      UpperCamelCase_             =      '''4.4'''
      UpperCamelCase_             =      '''train.py'''
      UpperCamelCase_             =      [
          '''--model_name_or_path''',
          '''bert''',
          '''--do_train''',
          '''False''',
          '''--epochs''',
          '''3''',
          '''--learning_rate''',
          '''5e-5''',
          '''--max_steps''',
          '''50.5''',
      ]
      UpperCamelCase_             =      [
          '''--model_name_or_path''',
          '''bert''',
          '''--do_train''',
          '''--do_test''',
          '''False''',
          '''--do_predict''',
          '''--epochs''',
          '''3''',
          '''--learning_rate''',
          '''5e-5''',
          '''--max_steps''',
          '''50.5''',
      ]





class UpperCAmelCase_       (     unittest.TestCase					):




      """simple docstring"""




      def 					A__   (			self      :		int		)	->	Dict:


       '''simple docstring'''

       lowercase       : str						=_convert_nargs_to_dict(MockLaunchConfig.success_training_script_args		)
       assert isinstance(converted_args['''model_name_or_path''']  ,   UpperCAmelCase		)
       assert isinstance(converted_args['''do_train''']  ,   UpperCAmelCase		)
       assert isinstance(converted_args['''epochs''']  ,   UpperCAmelCase		)
       assert isinstance(converted_args['''learning_rate''']  ,   UpperCAmelCase		)
       assert isinstance(converted_args['''max_steps''']  ,   UpperCAmelCase		)

       with pytest.raises(UpperCAmelCase		):
        _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args		)



