



"""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 SCREAMING_SNAKE_CASE__					(		__lowercase      ):



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		Tuple									=       self.config_class(**self.inputs_dict							)
             self.parent.assertTrue(hasattr(_lowercase						,     """hidden_sizes"""							)							)
             self.parent.assertTrue(hasattr(_lowercase						,     """neck_hidden_sizes"""							)							)
             self.parent.assertTrue(hasattr(_lowercase						,     """num_attention_heads"""							)							)







class SCREAMING_SNAKE_CASE__					:



      def __init__(self						,     _lowercase						,     _lowercase=13						,     _lowercase=32						,     _lowercase=2						,     _lowercase=3						,     _lowercase=640						,     _lowercase=4						,     _lowercase="silu"						,     _lowercase=3						,     _lowercase=32						,     _lowercase=0.1						,     _lowercase=0.1						,     _lowercase=0.1						,     _lowercase=0.02						,     _lowercase=True						,     _lowercase=True						,     _lowercase=10						,     _lowercase=None						,     ):





             '''simple docstring'''

             __a		:		int									=       parent
             __a		:		int									=       batch_size
             __a		:		Any									=       image_size
             __a		:		Optional[int]									=       patch_size
             __a		:		List[Any]									=       num_channels
             __a		:		Optional[Any]									=       last_hidden_size
             __a		:		Optional[int]									=       num_attention_heads
             __a		:		Any									=       hidden_act
             __a		:		Any									=       conv_kernel_size
             __a		:		str									=       output_stride
             __a		:		Dict									=       hidden_dropout_prob
             __a		:		Union[str, Any]									=       attention_probs_dropout_prob
             __a		:		List[str]									=       classifier_dropout_prob
             __a		:		str									=       use_labels
             __a		:		Any									=       is_training
             __a		:		Dict									=       num_labels
             __a		:		Union[str, Any]									=       initializer_range
             __a		:		Dict									=       scope



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		Tuple									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

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

             return config, pixel_values, labels, pixel_labels



      def     lowerCAmelCase__(self							):





             '''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     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							):





             '''simple docstring'''

             __a		:		List[Any]									=       MobileViTModel(config=_lowercase							)
             model.to(_lowercase							)
             model.eval()
             __a		:		List[Any]									=       model(_lowercase							)
             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						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							):





             '''simple docstring'''

             __a		:		int									=       self.num_labels
             __a		:		int									=       MobileViTForImageClassification(_lowercase							)
             model.to(_lowercase							)
             model.eval()
             __a		:		Union[str, Any]									=       model(_lowercase						,     labels=_lowercase							)
             self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)							)



      def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							):





             '''simple docstring'''

             __a		:		Union[str, Any]									=       self.num_labels
             __a		:		Any									=       MobileViTForSemanticSegmentation(_lowercase							)
             model.to(_lowercase							)
             model.eval()
             __a		:		str									=       model(_lowercase							)
             self.parent.assertEqual(
                 result.logits.shape						,     (
                     self.batch_size,
                     self.num_labels,
                     self.image_size // self.output_stride,
                     self.image_size // self.output_stride,
                 )						,     )
             __a		:		Tuple									=       model(_lowercase						,     labels=_lowercase							)
             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							):





             '''simple docstring'''

             __a		:		List[Any]									=       self.prepare_config_and_inputs()
             __a		:		Tuple									=       config_and_inputs
             __a		:		Tuple									=       {"pixel_values": pixel_values}
             return config, inputs_dict







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

      _lowerCAmelCase							=					False
      _lowerCAmelCase							=					False
      _lowerCAmelCase							=					False
      _lowerCAmelCase							=					False



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		str									=       MobileViTModelTester(self							)
             __a		:		int									=       MobileViTConfigTester(self						,     config_class=_lowercase						,     has_text_modality=_lowercase							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             self.config_tester.run_common_tests()



      @unittest.skip(reason="""MobileViT does not use inputs_embeds"""							)
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             pass



      @unittest.skip(reason="""MobileViT does not support input and output embeddings"""							)
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             pass



      @unittest.skip(reason="""MobileViT does not output attentions"""							)
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             pass



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		Any									=       self.model_tester.prepare_config_and_inputs_for_common()

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

                    __a		:		Dict									=       ["pixel_values"]
                    self.assertListEqual(arg_names[:1]						,     _lowercase							)



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





             '''simple docstring'''

             pass



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		Union[str, Any]									=       self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_lowercase							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             def check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							):
                    __a		:		str									=       model_class(_lowercase							)
                    model.to(_lowercase							)
                    model.eval()

                    with torch.no_grad():
                           __a		:		Any									=       model(**self._prepare_for_class(_lowercase						,     _lowercase							)							)

                    __a		:		Tuple									=       outputs.hidden_states

                    __a		:		Tuple									=       5
                    self.assertEqual(len(_lowercase							)						,     _lowercase							)

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

             __a		:		Any									=       self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    __a		:		str									=       True
                    check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							)

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

                    check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		Optional[Any]									=       self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_lowercase							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		List[str]									=       self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase							)





      @slow
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    __a		:		List[str]									=       MobileViTModel.from_pretrained(_lowercase							)
                    self.assertIsNotNone(_lowercase							)







def       __magic_name__    (   ):
       __a		:		List[Any]									=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
       return image







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



      @cached_property
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

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



      @slow
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		List[Any]									=       MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""							).to(_lowercase							)

             __a		:		Dict									=       self.default_image_processor
             __a		:		Optional[Any]									=       prepare_img()
             __a		:		Union[str, Any]									=       image_processor(images=_lowercase						,     return_tensors="""pt"""							).to(_lowercase							)

             # forward pass
             with torch.no_grad():
                    __a		:		str									=       model(**_lowercase							)

             # verify the logits
             __a		:		Optional[int]									=       torch.Size((1, 1000)							)
             self.assertEqual(outputs.logits.shape						,     _lowercase							)

             __a		:		List[str]									=       torch.tensor([-1.9364, -1.2327, -0.4653]							).to(_lowercase							)

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



      @slow
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		Optional[Any]									=       MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)
             __a		:		Optional[int]									=       model.to(_lowercase							)

             __a		:		str									=       MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)

             __a		:		List[Any]									=       prepare_img()
             __a		:		Tuple									=       image_processor(images=_lowercase						,     return_tensors="""pt"""							).to(_lowercase							)

             # forward pass
             with torch.no_grad():
                    __a		:		int									=       model(**_lowercase							)
             __a		:		Any									=       outputs.logits

             # verify the logits
             __a		:		List[Any]									=       torch.Size((1, 21, 32, 32)							)
             self.assertEqual(logits.shape						,     _lowercase							)

             __a		:		Optional[Any]									=       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=_lowercase						,     )

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





      @slow
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		int									=       MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)
             __a		:		str									=       model.to(_lowercase							)

             __a		:		str									=       MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""							)

             __a		:		List[str]									=       prepare_img()
             __a		:		List[Any]									=       image_processor(images=_lowercase						,     return_tensors="""pt"""							).to(_lowercase							)

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

             __a		:		List[str]									=       outputs.logits.detach().cpu()

             __a		:		Any									=       image_processor.post_process_semantic_segmentation(outputs=_lowercase						,     target_sizes=[(50, 60)]							)
             __a		:		Optional[Any]									=       torch.Size((50, 60)							)
             self.assertEqual(segmentation[0].shape						,     _lowercase							)

             __a		:		Optional[Any]									=       image_processor.post_process_semantic_segmentation(outputs=_lowercase							)
             __a		:		Union[str, Any]									=       torch.Size((32, 32)							)
             self.assertEqual(segmentation[0].shape						,     _lowercase							)






"""simple docstring"""

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available


lowercase__			   =  {
    "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	lowercase__			   =  [
	    "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
	    "ErnieForCausalLM",
	    "ErnieForMaskedLM",
	    "ErnieForMultipleChoice",
	    "ErnieForNextSentencePrediction",
	    "ErnieForPreTraining",
	    "ErnieForQuestionAnswering",
	    "ErnieForSequenceClassification",
	    "ErnieForTokenClassification",
	    "ErnieModel",
	    "ErniePreTrainedModel",
	]

if TYPE_CHECKING:
	from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_ernie import (
		    ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
		    ErnieForCausalLM,
		    ErnieForMaskedLM,
		    ErnieForMultipleChoice,
		    ErnieForNextSentencePrediction,
		    ErnieForPreTraining,
		    ErnieForQuestionAnswering,
		    ErnieForSequenceClassification,
		    ErnieForTokenClassification,
		    ErnieModel,
		    ErniePreTrainedModel,
		)

else:
	import sys

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

