




'''simple docstring'''






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_      (						_SCREAMING_SNAKE_CASE							):





     def 			_lowerCAmelCase      (     self     :					Optional[Any]			):
           snake_case__       :   Union[str, Any]	      =    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     :					Any     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					List[Any]=13     ,							__lowerCamelCase     :					str=32     ,							__lowerCamelCase     :					str=2     ,							__lowerCamelCase     :					List[Any]=3     ,							__lowerCamelCase     :					List[str]=640     ,							__lowerCamelCase     :					Union[str, Any]=4     ,							__lowerCamelCase     :					Dict="silu"     ,							__lowerCamelCase     :					List[str]=3     ,							__lowerCamelCase     :					str=32     ,							__lowerCamelCase     :					Any=0.1     ,							__lowerCamelCase     :					List[str]=0.1     ,							__lowerCamelCase     :					Union[str, Any]=0.1     ,							__lowerCamelCase     :					Optional[Any]=0.0_2     ,							__lowerCamelCase     :					Union[str, Any]=True     ,							__lowerCamelCase     :					Optional[int]=True     ,							__lowerCamelCase     :					Any=10     ,							__lowerCamelCase     :					str=None     ,							):
           snake_case__       :   Union[str, Any]	      =    parent
           snake_case__       :   Union[str, Any]	      =    batch_size
           snake_case__       :   Tuple	      =    image_size
           snake_case__       :   int	      =    patch_size
           snake_case__       :   Optional[int]	      =    num_channels
           snake_case__       :   Optional[Any]	      =    last_hidden_size
           snake_case__       :   Optional[int]	      =    num_attention_heads
           snake_case__       :   Any	      =    hidden_act
           snake_case__       :   Dict	      =    conv_kernel_size
           snake_case__       :   List[Any]	      =    output_stride
           snake_case__       :   List[str]	      =    hidden_dropout_prob
           snake_case__       :   List[str]	      =    attention_probs_dropout_prob
           snake_case__       :   int	      =    classifier_dropout_prob
           snake_case__       :   str	      =    use_labels
           snake_case__       :   Any	      =    is_training
           snake_case__       :   int	      =    num_labels
           snake_case__       :   int	      =    initializer_range
           snake_case__       :   Tuple	      =    scope





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           snake_case__       :   int	      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

           snake_case__       :   List[str]	      =    self.get_config()

           return config, pixel_values, labels, pixel_labels





     def 			_lowerCAmelCase      (     self     :					Optional[int]			):
           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 			_lowerCAmelCase      (     self     :					Dict     ,							__lowerCamelCase     :					Union[str, Any]     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					List[str]			):
           snake_case__       :   Optional[int]	      =    MobileViTModel(config=_lowerCAmelCase			)
           model.to(_lowerCAmelCase			)
           model.eval()
           snake_case__       :   int	      =    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     :					Union[str, Any]     ,							__lowerCamelCase     :					Union[str, Any]     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					str			):
           snake_case__       :   str	      =    self.num_labels
           snake_case__       :   List[str]	      =    MobileViTForImageClassification(_lowerCAmelCase			)
           model.to(_lowerCAmelCase			)
           model.eval()
           snake_case__       :   Union[str, Any]	      =    model(_lowerCAmelCase     ,							labels=_lowerCAmelCase			)
           self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)			)





     def 			_lowerCAmelCase      (     self     :					int     ,							__lowerCamelCase     :					Union[str, Any]     ,							__lowerCamelCase     :					Any     ,							__lowerCamelCase     :					Optional[Any]     ,							__lowerCamelCase     :					List[str]			):
           snake_case__       :   Optional[Any]	      =    self.num_labels
           snake_case__       :   List[Any]	      =    MobileViTForSemanticSegmentation(_lowerCAmelCase			)
           model.to(_lowerCAmelCase			)
           model.eval()
           snake_case__       :   List[str]	      =    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,
               )     ,							)
           snake_case__       :   int	      =    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			):
           snake_case__       :   Tuple	      =    self.prepare_config_and_inputs()
           snake_case__      ,							snake_case__      ,							snake_case__      ,							snake_case__       :   List[str]	      =    config_and_inputs
           snake_case__       :   Optional[Any]	      =    {'pixel_values': pixel_values}
           return config, inputs_dict






@require_torch
class        lowercase_      (						_SCREAMING_SNAKE_CASE						,       _SCREAMING_SNAKE_CASE						,       unittest.TestCase							):
     A_											=			(
         (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     A_											=			(
         {
             "feature-extraction": MobileViTModel,
             "image-classification": MobileViTForImageClassification,
             "image-segmentation": MobileViTForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     A_											=			False
     A_											=			False
     A_											=			False
     A_											=			False





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           snake_case__       :   Tuple	      =    MobileViTModelTester(self			)
           snake_case__       :   List[str]	      =    MobileViTConfigTester(self     ,							config_class=_lowerCAmelCase     ,							has_text_modality=_lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					Union[str, Any]			):
           self.config_tester.run_common_tests()





     @unittest.skip(reason='MobileViT does not use inputs_embeds'			)
     def 			_lowerCAmelCase      (     self     :					Tuple			):
           pass





     @unittest.skip(reason='MobileViT does not support input and output embeddings'			)
     def 			_lowerCAmelCase      (     self     :					Dict			):
           pass





     @unittest.skip(reason='MobileViT does not output attentions'			)
     def 			_lowerCAmelCase      (     self     :					List[str]			):
           pass





     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__      ,							snake_case__       :   Any	      =    self.model_tester.prepare_config_and_inputs_for_common()

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

                 snake_case__       :   int	      =    ['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 			_lowerCAmelCase      (     self     :					int			):
           pass





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           snake_case__       :   Optional[Any]	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					Optional[int]			):
           def check_hidden_states_output(__lowerCamelCase     :					int     ,							__lowerCamelCase     :					Tuple     ,							__lowerCamelCase     :					List[str]			):
                 snake_case__       :   List[Any]	      =    model_class(_lowerCAmelCase			)
                 model.to(_lowerCAmelCase			)
                 model.eval()

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

                 snake_case__       :   Any	      =    outputs.hidden_states

                 snake_case__       :   Any	      =    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.
                 snake_case__       :   Tuple	      =    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			)

           snake_case__      ,							snake_case__       :   int	      =    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 snake_case__       :   Any	      =    True
                 check_hidden_states_output(_lowerCAmelCase     ,							_lowerCAmelCase     ,							_lowerCAmelCase			)

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

                 check_hidden_states_output(_lowerCAmelCase     ,							_lowerCAmelCase     ,							_lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   Tuple	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase			)





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   Tuple	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCAmelCase			)





     @slow
     def 			_lowerCAmelCase      (     self     :					Dict			):
           for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case__       :   Optional[Any]	      =    MobileViTModel.from_pretrained(_lowerCAmelCase			)
                 self.assertIsNotNone(_lowerCAmelCase			)






def 		UpperCamelCase__      (		)    ->   Union[str, Any]:
      snake_case__       :   Any	      =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
      return image






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





     @cached_property
     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'			) if is_vision_available() else None





     @slow
     def 			_lowerCAmelCase      (     self     :					Optional[int]			):
           snake_case__       :   List[str]	      =    MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'			).to(_lowerCAmelCase			)

           snake_case__       :   Dict	      =    self.default_image_processor
           snake_case__       :   int	      =    prepare_img()
           snake_case__       :   Optional[Any]	      =    image_processor(images=_lowerCAmelCase     ,							return_tensors='pt'			).to(_lowerCAmelCase			)

           # forward pass
           with torch.no_grad():
                 snake_case__       :   List[str]	      =    model(**_lowerCAmelCase			)

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

           snake_case__       :   List[str]	      =    torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]			).to(_lowerCAmelCase			)

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





     @slow
     def 			_lowerCAmelCase      (     self     :					Any			):
           snake_case__       :   int	      =    MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)
           snake_case__       :   List[Any]	      =    model.to(_lowerCAmelCase			)

           snake_case__       :   Union[str, Any]	      =    MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)

           snake_case__       :   str	      =    prepare_img()
           snake_case__       :   Optional[int]	      =    image_processor(images=_lowerCAmelCase     ,							return_tensors='pt'			).to(_lowerCAmelCase			)

           # forward pass
           with torch.no_grad():
                 snake_case__       :   Any	      =    model(**_lowerCAmelCase			)
           snake_case__       :   List[Any]	      =    outputs.logits

           # verify the logits
           snake_case__       :   Optional[int]	      =    torch.Size((1, 21, 32, 32)			)
           self.assertEqual(logits.shape     ,							_lowerCAmelCase			)

           snake_case__       :   Any	      =    torch.tensor(
               [
                   [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
                   [[-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_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
                   [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
               ]     ,							device=_lowerCAmelCase     ,							)

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





     @slow
     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   Optional[int]	      =    MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)
           snake_case__       :   Union[str, Any]	      =    model.to(_lowerCAmelCase			)

           snake_case__       :   Optional[Any]	      =    MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)

           snake_case__       :   Optional[Any]	      =    prepare_img()
           snake_case__       :   Tuple	      =    image_processor(images=_lowerCAmelCase     ,							return_tensors='pt'			).to(_lowerCAmelCase			)

           # forward pass
           with torch.no_grad():
                 snake_case__       :   List[Any]	      =    model(**_lowerCAmelCase			)

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

           snake_case__       :   Union[str, Any]	      =    image_processor.post_process_semantic_segmentation(outputs=_lowerCAmelCase     ,							target_sizes=[(50, 60)]			)
           snake_case__       :   int	      =    torch.Size((50, 60)			)
           self.assertEqual(segmentation[0].shape     ,							_lowerCAmelCase			)

           snake_case__       :   str	      =    image_processor.post_process_semantic_segmentation(outputs=_lowerCAmelCase			)
           snake_case__       :   List[Any]	      =    torch.Size((32, 32)			)
           self.assertEqual(segmentation[0].shape     ,							_lowerCAmelCase			)






import warnings

from ...utils import logging
from .image_processing_layoutlmva import LayoutLMvaImageProcessor


lowerCamelCase__					:  Union[str, Any]      							=				logging.get_logger(__name__)





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 def __init__(				self    :						Dict							,							*_lowerCAmelCase    :						Optional[Any]							,							**_lowerCAmelCase    :						Any		):
       warnings.warn(
           'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
           ' Please use LayoutLMv2ImageProcessor instead.'							,							_lowerCAmelCase							,							)
       super().__init__(*_lowerCAmelCase							,							**_lowerCAmelCase		)