
"""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   __a  (      _lowerCAmelCase	):






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







              """simple docstring"""
              UpperCamelCase					 =		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   __a  :






       def __init__(  self :							int       ,      UpperCAmelCase_ :							str       ,      UpperCAmelCase_ :							str=13       ,      UpperCAmelCase_ :							int=32       ,      UpperCAmelCase_ :							List[str]=2       ,      UpperCAmelCase_ :							List[str]=3       ,      UpperCAmelCase_ :							Dict=640       ,      UpperCAmelCase_ :							Dict=4       ,      UpperCAmelCase_ :							Dict="silu"       ,      UpperCAmelCase_ :							List[Any]=3       ,      UpperCAmelCase_ :							Union[str, Any]=32       ,      UpperCAmelCase_ :							int=0.1       ,      UpperCAmelCase_ :							Optional[int]=0.1       ,      UpperCAmelCase_ :							Any=0.1       ,      UpperCAmelCase_ :							str=0.02       ,      UpperCAmelCase_ :							int=True       ,      UpperCAmelCase_ :							Optional[Any]=True       ,      UpperCAmelCase_ :							str=10       ,      UpperCAmelCase_ :							List[Any]=None       ,      )->  int:







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







              """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 	_SCREAMING_SNAKE_CASE       (  self :							int			)->  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 	_SCREAMING_SNAKE_CASE       (  self :							Dict       ,      UpperCAmelCase_ :							int       ,      UpperCAmelCase_ :							Optional[int]       ,      UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							Dict			)->  List[Any]:







              """simple docstring"""
              UpperCamelCase					 =		MobileViTModel(config=UpperCAmelCase_			)
              model.to(UpperCAmelCase_			)
              model.eval()
              UpperCamelCase					 =		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 	_SCREAMING_SNAKE_CASE       (  self :							Any       ,      UpperCAmelCase_ :							Optional[int]       ,      UpperCAmelCase_ :							List[Any]       ,      UpperCAmelCase_ :							List[Any]       ,      UpperCAmelCase_ :							Any			)->  Optional[Any]:







              """simple docstring"""
              UpperCamelCase					 =		self.num_labels
              UpperCamelCase					 =		MobileViTForImageClassification(UpperCAmelCase_			)
              model.to(UpperCAmelCase_			)
              model.eval()
              UpperCamelCase					 =		model(UpperCAmelCase_       ,      labels=UpperCAmelCase_			)
              self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.num_labels)			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Union[str, Any]       ,      UpperCAmelCase_ :							List[Any]       ,      UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							Optional[Any]       ,      UpperCAmelCase_ :							Union[str, Any]			)->  Dict:







              """simple docstring"""
              UpperCamelCase					 =		self.num_labels
              UpperCamelCase					 =		MobileViTForSemanticSegmentation(UpperCAmelCase_			)
              model.to(UpperCAmelCase_			)
              model.eval()
              UpperCamelCase					 =		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,
                  )       ,      )
              UpperCamelCase					 =		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 	_SCREAMING_SNAKE_CASE       (  self :							Optional[int]			)->  Any:







              """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   __a  (      _lowerCAmelCase    ,     _lowerCAmelCase    ,     unittest.TestCase	):
       UpperCamelCase_		:					Union[str, Any]   =			(
           (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       UpperCamelCase_		:					List[str]   =			(
           {
               '''feature-extraction''': MobileViTModel,
               '''image-classification''': MobileViTForImageClassification,
               '''image-segmentation''': MobileViTForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       UpperCamelCase_		:					Optional[int]   =			False
       UpperCamelCase_		:					Tuple   =			False
       UpperCamelCase_		:					Union[str, Any]   =			False
       UpperCamelCase_		:					List[str]   =			False






       def 	_SCREAMING_SNAKE_CASE       (  self :							Any			)->  Dict:







              """simple docstring"""
              UpperCamelCase					 =		MobileViTModelTester(self			)
              UpperCamelCase					 =		MobileViTConfigTester(self       ,      config_class=UpperCAmelCase_       ,      has_text_modality=UpperCAmelCase_			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Union[str, Any]			)->  Optional[int]:







              """simple docstring"""
              self.config_tester.run_common_tests()






       @unittest.skip(reason="MobileViT does not use inputs_embeds"			)
       def 	_SCREAMING_SNAKE_CASE       (  self :							Union[str, Any]			)->  List[str]:







              """simple docstring"""
              pass






       @unittest.skip(reason="MobileViT does not support input and output embeddings"			)
       def 	_SCREAMING_SNAKE_CASE       (  self :							str			)->  List[str]:







              """simple docstring"""
              pass






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







              """simple docstring"""
              pass






       def 	_SCREAMING_SNAKE_CASE       (  self :							Tuple			)->  Tuple:







              """simple docstring"""
              UpperCamelCase ,       UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs_for_common()

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






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







              """simple docstring"""
              pass






       def 	_SCREAMING_SNAKE_CASE       (  self :							str			)->  int:







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*UpperCAmelCase_			)






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







              """simple docstring"""
              def check_hidden_states_output(UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							Optional[Any]       ,      UpperCAmelCase_ :							Union[str, Any]			):
                     UpperCamelCase					 =		model_class(UpperCAmelCase_			)
                     model.to(UpperCAmelCase_			)
                     model.eval()

                     with torch.no_grad():
                            UpperCamelCase					 =		model(**self._prepare_for_class(UpperCAmelCase_       ,      UpperCAmelCase_			)			)

                     UpperCamelCase					 =		outputs.hidden_states

                     UpperCamelCase					 =		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.
                     UpperCamelCase					 =		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			)

              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(UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_			)

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

                     check_hidden_states_output(UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Dict			)->  Optional[Any]:







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Dict			)->  Tuple:







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_			)






       @slow
       def 	_SCREAMING_SNAKE_CASE       (  self :							Tuple			)->  Dict:







              """simple docstring"""
              for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase					 =		MobileViTModel.from_pretrained(UpperCAmelCase_			)
                     self.assertIsNotNone(UpperCAmelCase_			)





def 	lowerCamelCase__			(							)->							Dict:







       """simple docstring"""
       UpperCamelCase					 =		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
       return image



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






       @cached_property
       def 	_SCREAMING_SNAKE_CASE       (  self :							Optional[Any]			)->  Optional[int]:







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






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







              """simple docstring"""
              UpperCamelCase					 =		MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"			).to(UpperCAmelCase_			)

              UpperCamelCase					 =		self.default_image_processor
              UpperCamelCase					 =		prepare_img()
              UpperCamelCase					 =		image_processor(images=UpperCAmelCase_       ,      return_tensors="pt"			).to(UpperCAmelCase_			)

              # forward pass
              with torch.no_grad():
                     UpperCamelCase					 =		model(**UpperCAmelCase_			)

              # verify the logits
              UpperCamelCase					 =		torch.Size((1, 1_000)			)
              self.assertEqual(outputs.logits.shape       ,      UpperCAmelCase_			)

              UpperCamelCase					 =		torch.tensor([-1.9364, -1.2327, -0.4653]			).to(UpperCAmelCase_			)

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






       @slow
       def 	_SCREAMING_SNAKE_CASE       (  self :							Tuple			)->  Optional[int]:







              """simple docstring"""
              UpperCamelCase					 =		MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"			)
              UpperCamelCase					 =		model.to(UpperCAmelCase_			)

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

              UpperCamelCase					 =		prepare_img()
              UpperCamelCase					 =		image_processor(images=UpperCAmelCase_       ,      return_tensors="pt"			).to(UpperCAmelCase_			)

              # forward pass
              with torch.no_grad():
                     UpperCamelCase					 =		model(**UpperCAmelCase_			)
              UpperCamelCase					 =		outputs.logits

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

              UpperCamelCase					 =		torch.tensor(
                  [
                      [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
                      [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
                      [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
                  ]       ,      device=UpperCAmelCase_       ,      )

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






       @slow
       def 	_SCREAMING_SNAKE_CASE       (  self :							str			)->  Any:







              """simple docstring"""
              UpperCamelCase					 =		MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"			)
              UpperCamelCase					 =		model.to(UpperCAmelCase_			)

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

              UpperCamelCase					 =		prepare_img()
              UpperCamelCase					 =		image_processor(images=UpperCAmelCase_       ,      return_tensors="pt"			).to(UpperCAmelCase_			)

              # forward pass
              with torch.no_grad():
                     UpperCamelCase					 =		model(**UpperCAmelCase_			)

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

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

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







"""simple docstring"""


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


SCREAMING_SNAKE_CASE      =     {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE      =     ["""MBartTokenizer"""]

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE      =     ["""MBartTokenizerFast"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE      =     [
          """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """MBartForCausalLM""",
          """MBartForConditionalGeneration""",
          """MBartForQuestionAnswering""",
          """MBartForSequenceClassification""",
          """MBartModel""",
          """MBartPreTrainedModel""",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE      =     [
          """TFMBartForConditionalGeneration""",
          """TFMBartModel""",
          """TFMBartPreTrainedModel""",
      ]

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE      =     [
          """FlaxMBartForConditionalGeneration""",
          """FlaxMBartForQuestionAnswering""",
          """FlaxMBartForSequenceClassification""",
          """FlaxMBartModel""",
          """FlaxMBartPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_mbart import MBartTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_mbart_fast import MBartTokenizerFast

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_mbart import (
                MBART_PRETRAINED_MODEL_ARCHIVE_LIST,
                MBartForCausalLM,
                MBartForConditionalGeneration,
                MBartForQuestionAnswering,
                MBartForSequenceClassification,
                MBartModel,
                MBartPreTrainedModel,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel

      try:
            if not is_flax_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_flax_mbart import (
                FlaxMBartForConditionalGeneration,
                FlaxMBartForQuestionAnswering,
                FlaxMBartForSequenceClassification,
                FlaxMBartModel,
                FlaxMBartPreTrainedModel,
            )

else:
      import sys

      SCREAMING_SNAKE_CASE      =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





