






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







    """simple docstring"""







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    self.config_class(**self.inputs_dict )
           self.parent.assertTrue(hasattr(UpperCamelCase_				,    'hidden_sizes' ) )
           self.parent.assertTrue(hasattr(UpperCamelCase_				,    'neck_hidden_sizes' ) )
           self.parent.assertTrue(hasattr(UpperCamelCase_				,    'num_attention_heads' ) )



class        UpperCamelCase__ :







    """simple docstring"""







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





           '''simple docstring'''

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







    def 				a__			(		self :	Any ):





           '''simple docstring'''

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

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

           __magic_name__      				=    self.get_config()

           return config, pixel_values, labels, pixel_labels







    def 				a__			(		self :	Tuple ):





           '''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 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Union[str, Any] ):





           '''simple docstring'''

           __magic_name__      				=    MobileViTModel(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           __magic_name__      				=    model(UpperCamelCase_ )
           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 				a__			(		self :	Dict				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	str ):





           '''simple docstring'''

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







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	str ):





           '''simple docstring'''

           __magic_name__      				=    self.num_labels
           __magic_name__      				=    MobileViTForSemanticSegmentation(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           __magic_name__      				=    model(UpperCamelCase_ )
           self.parent.assertEqual(
               result.logits.shape				,    (
                   self.batch_size,
                   self.num_labels,
                   self.image_size // self.output_stride,
                   self.image_size // self.output_stride,
               )				,    )
           __magic_name__      				=    model(UpperCamelCase_				,    labels=UpperCamelCase_ )
           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 				a__			(		self :	str ):





           '''simple docstring'''

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



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







    """simple docstring"""
    __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 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           __magic_name__      				=    MobileViTModelTester(self )
           __magic_name__      				=    MobileViTConfigTester(self				,    config_class=UpperCamelCase_				,    has_text_modality=UpperCamelCase_ )







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           self.config_tester.run_common_tests()







    @unittest.skip(reason='MobileViT does not use inputs_embeds' )
    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           pass







    @unittest.skip(reason='MobileViT does not support input and output embeddings' )
    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

           pass







    @unittest.skip(reason='MobileViT does not output attentions' )
    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

           pass







    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

           __magic_name__				,  __magic_name__      				=    self.model_tester.prepare_config_and_inputs_for_common()

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

                  __magic_name__      				=    ['pixel_values']
                  self.assertListEqual(arg_names[:1]				,    UpperCamelCase_ )







    @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           pass







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

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







    def 				a__			(		self :	int ):





           '''simple docstring'''

           def check_hidden_states_output(UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	List[Any] ):
                  __magic_name__      				=    model_class(UpperCamelCase_ )
                  model.to(UpperCamelCase_ )
                  model.eval()

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

                  __magic_name__      				=    outputs.hidden_states

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

                  # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
                  # with the width and height being successively divided by 2.
                  __magic_name__      				=    2
                  for i in range(len(UpperCamelCase_ ) ):
                         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 )

           __magic_name__				,  __magic_name__      				=    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  __magic_name__      				=    True
                  check_hidden_states_output(UpperCamelCase_				,    UpperCamelCase_				,    UpperCamelCase_ )

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

                  check_hidden_states_output(UpperCamelCase_				,    UpperCamelCase_				,    UpperCamelCase_ )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

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







    def 				a__			(		self :	Any ):





           '''simple docstring'''

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







    @slow
    def 				a__			(		self :	int ):





           '''simple docstring'''

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


def 							A						(				)    ->		List[Any]:

       """simple docstring"""





       __magic_name__      				=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
       return image






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







    """simple docstring"""







    @cached_property
    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

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







    @slow
    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(UpperCamelCase_ )

           __magic_name__      				=    self.default_image_processor
           __magic_name__      				=    prepare_img()
           __magic_name__      				=    image_processor(images=UpperCamelCase_				,    return_tensors='pt' ).to(UpperCamelCase_ )

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

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

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

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







    @slow
    def 				a__			(		self :	Optional[Any] ):





           '''simple docstring'''

           __magic_name__      				=    MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
           __magic_name__      				=    model.to(UpperCamelCase_ )

           __magic_name__      				=    MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )

           __magic_name__      				=    prepare_img()
           __magic_name__      				=    image_processor(images=UpperCamelCase_				,    return_tensors='pt' ).to(UpperCamelCase_ )

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

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

           __magic_name__      				=    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]],
                   [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
                   [[-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=UpperCamelCase_				,    )

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







    @slow
    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

           __magic_name__      				=    MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
           __magic_name__      				=    model.to(UpperCamelCase_ )

           __magic_name__      				=    MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )

           __magic_name__      				=    prepare_img()
           __magic_name__      				=    image_processor(images=UpperCamelCase_				,    return_tensors='pt' ).to(UpperCamelCase_ )

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

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

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

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







"""simple docstring"""
from ..utils import DummyObject, requires_backends



class        UpperCamelCase__ (				metaclass=a_):







    """simple docstring"""
    __UpperCAmelCase           = ["""flax""", """transformers"""]







    def __init__(		self :	List[Any]				,    *UpperCamelCase_ :	str				,    **UpperCamelCase_ :	Any ):





           '''simple docstring'''

           requires_backends(self				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	Optional[int]				,    *UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	str				,    *UpperCamelCase_ :	Optional[Any]				,    **UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )



class        UpperCamelCase__ (				metaclass=a_):







    """simple docstring"""
    __UpperCAmelCase           = ["""flax""", """transformers"""]







    def __init__(		self :	List[Any]				,    *UpperCamelCase_ :	str				,    **UpperCamelCase_ :	str ):





           '''simple docstring'''

           requires_backends(self				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	Optional[int]				,    *UpperCamelCase_ :	Optional[int]				,    **UpperCamelCase_ :	List[str] ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	Tuple				,    *UpperCamelCase_ :	List[str]				,    **UpperCamelCase_ :	Optional[Any] ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )



class        UpperCamelCase__ (				metaclass=a_):







    """simple docstring"""
    __UpperCAmelCase           = ["""flax""", """transformers"""]







    def __init__(		self :	Optional[int]				,    *UpperCamelCase_ :	List[Any]				,    **UpperCamelCase_ :	List[str] ):





           '''simple docstring'''

           requires_backends(self				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	str				,    *UpperCamelCase_ :	List[str]				,    **UpperCamelCase_ :	Tuple ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	Tuple				,    *UpperCamelCase_ :	Any				,    **UpperCamelCase_ :	List[str] ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )



class        UpperCamelCase__ (				metaclass=a_):







    """simple docstring"""
    __UpperCAmelCase           = ["""flax""", """transformers"""]







    def __init__(		self :	Optional[Any]				,    *UpperCamelCase_ :	Optional[Any]				,    **UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           requires_backends(self				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	str				,    *UpperCamelCase_ :	Dict				,    **UpperCamelCase_ :	List[str] ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )







    @classmethod
    def 				a__			(		cls :	str				,    *UpperCamelCase_ :	Optional[Any]				,    **UpperCamelCase_ :	Union[str, Any] ):





           '''simple docstring'''

           requires_backends(cls				,    ['flax', 'transformers'] )