

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




				def     a							(					self       ):
											snake_case_							=    self.config_class(**self.inputs_dict       )
											self.parent.assertTrue(hasattr(__A      ,   'hidden_sizes'       )       )
											self.parent.assertTrue(hasattr(__A      ,   'neck_hidden_sizes'       )       )
											self.parent.assertTrue(hasattr(__A      ,   'num_attention_heads'       )       )







class  lowercase				:




				def __init__(					self      ,   snake_case      ,   snake_case=13      ,   snake_case=32      ,   snake_case=2      ,   snake_case=3      ,   snake_case=640      ,   snake_case=4      ,   snake_case="silu"      ,   snake_case=3      ,   snake_case=32      ,   snake_case=0.1      ,   snake_case=0.1      ,   snake_case=0.1      ,   snake_case=0.02      ,   snake_case=True      ,   snake_case=True      ,   snake_case=10      ,   snake_case=None      ,   ):
											snake_case_							=    parent
											snake_case_							=    batch_size
											snake_case_							=    image_size
											snake_case_							=    patch_size
											snake_case_							=    num_channels
											snake_case_							=    last_hidden_size
											snake_case_							=    num_attention_heads
											snake_case_							=    hidden_act
											snake_case_							=    conv_kernel_size
											snake_case_							=    output_stride
											snake_case_							=    hidden_dropout_prob
											snake_case_							=    attention_probs_dropout_prob
											snake_case_							=    classifier_dropout_prob
											snake_case_							=    use_labels
											snake_case_							=    is_training
											snake_case_							=    num_labels
											snake_case_							=    initializer_range
											snake_case_							=    scope




				def     a							(					self       ):
											snake_case_							=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

											snake_case_							=    self.get_config()

											return config, pixel_values, labels, pixel_labels




				def     a							(					self       ):
											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      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case       ):
											snake_case_							=    MobileViTModel(config=__A       )
											model.to(__A       )
											model.eval()
											snake_case_							=    model(__A       )
											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      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case       ):
											snake_case_							=    self.num_labels
											snake_case_							=    MobileViTForImageClassification(__A       )
											model.to(__A       )
											model.eval()
											snake_case_							=    model(__A      ,   labels=__A       )
											self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels)       )




				def     a							(					self      ,   snake_case      ,   snake_case      ,   snake_case      ,   snake_case       ):
											snake_case_							=    self.num_labels
											snake_case_							=    MobileViTForSemanticSegmentation(__A       )
											model.to(__A       )
											model.eval()
											snake_case_							=    model(__A       )
											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_							=    model(__A      ,   labels=__A       )
											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       ):
											snake_case_							=    self.prepare_config_and_inputs()
											snake_case_							=    config_and_inputs
											snake_case_							=    {"pixel_values": pixel_values}
											return config, inputs_dict







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

				__SCREAMING_SNAKE_CASE					: Union[str, Any]       			=			False
				__SCREAMING_SNAKE_CASE					: Dict       			=			False
				__SCREAMING_SNAKE_CASE					: List[Any]       			=			False
				__SCREAMING_SNAKE_CASE					: Union[str, Any]       			=			False




				def     a							(					self       ):
											snake_case_							=    MobileViTModelTester(self       )
											snake_case_							=    MobileViTConfigTester(self      ,   config_class=__A      ,   has_text_modality=__A       )




				def     a							(					self       ):
											self.config_tester.run_common_tests()




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




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




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




				def     a							(					self       ):
											snake_case_							=    self.model_tester.prepare_config_and_inputs_for_common()

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

																		snake_case_							=    ["pixel_values"]
																		self.assertListEqual(arg_names[:1]      ,   __A       )




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




				def     a							(					self       ):
											snake_case_							=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__A       )




				def     a							(					self       ):





											def check_hidden_states_output(snake_case      ,   snake_case      ,   snake_case       ):
																		snake_case_							=    model_class(__A       )
																		model.to(__A       )
																		model.eval()

																		with torch.no_grad():
																									snake_case_							=    model(**self._prepare_for_class(__A      ,   __A       )       )

																		snake_case_							=    outputs.hidden_states

																		snake_case_							=    5
																		self.assertEqual(len(__A       )      ,   __A       )

																		# 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_							=    2
																		for i in range(len(__A       )       ):
																									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_							=    self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		snake_case_							=    True
																		check_hidden_states_output(__A      ,   __A      ,   __A       )

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

																		check_hidden_states_output(__A      ,   __A      ,   __A       )




				def     a							(					self       ):
											snake_case_							=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__A       )




				def     a							(					self       ):
											snake_case_							=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*__A       )




				@slow
				def     a							(					self       ):





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





def 					__lowerCamelCase	( ):







							'''simple docstring'''






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







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




				@cached_property
				def     a							(					self       ):
											return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'       ) if is_vision_available() else None




				@slow
				def     a							(					self       ):
											snake_case_							=    MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'       ).to(__A       )

											snake_case_							=    self.default_image_processor
											snake_case_							=    prepare_img()
											snake_case_							=    image_processor(images=__A      ,   return_tensors='pt'       ).to(__A       )

											# forward pass
											with torch.no_grad():
																		snake_case_							=    model(**__A       )

											# verify the logits
											snake_case_							=    torch.Size((1, 1000)       )
											self.assertEqual(outputs.logits.shape      ,   __A       )

											snake_case_							=    torch.tensor([-1.93_64, -1.23_27, -0.46_53]       ).to(__A       )

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




				@slow
				def     a							(					self       ):
											snake_case_							=    MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'       )
											snake_case_							=    model.to(__A       )

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

											snake_case_							=    prepare_img()
											snake_case_							=    image_processor(images=__A      ,   return_tensors='pt'       ).to(__A       )

											# forward pass
											with torch.no_grad():
																		snake_case_							=    model(**__A       )
											snake_case_							=    outputs.logits

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

											snake_case_							=    torch.tensor(
											    [
											        [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
											        [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
											        [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
											    ]      ,   device=__A      ,   )

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




				@slow
				def     a							(					self       ):
											snake_case_							=    MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'       )
											snake_case_							=    model.to(__A       )

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

											snake_case_							=    prepare_img()
											snake_case_							=    image_processor(images=__A      ,   return_tensors='pt'       ).to(__A       )

											# forward pass
											with torch.no_grad():
																		snake_case_							=    model(**__A       )

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

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

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








from typing import TYPE_CHECKING

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


_snake_case             =     {
    '''configuration_squeezebert''': [
        '''SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''SqueezeBertConfig''',
        '''SqueezeBertOnnxConfig''',
    ],
    '''tokenization_squeezebert''': ['''SqueezeBertTokenizer'''],
}

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _snake_case             =     ['''SqueezeBertTokenizerFast''']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _snake_case             =     [
       '''SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''SqueezeBertForMaskedLM''',
       '''SqueezeBertForMultipleChoice''',
       '''SqueezeBertForQuestionAnswering''',
       '''SqueezeBertForSequenceClassification''',
       '''SqueezeBertForTokenClassification''',
       '''SqueezeBertModel''',
       '''SqueezeBertModule''',
       '''SqueezeBertPreTrainedModel''',
   ]


if TYPE_CHECKING:
   from .configuration_squeezebert import (
       SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
       SqueezeBertConfig,
       SqueezeBertOnnxConfig,
   )
   from .tokenization_squeezebert import SqueezeBertTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_squeezebert import (
          SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          SqueezeBertForMaskedLM,
          SqueezeBertForMultipleChoice,
          SqueezeBertForQuestionAnswering,
          SqueezeBertForSequenceClassification,
          SqueezeBertForTokenClassification,
          SqueezeBertModel,
          SqueezeBertModule,
          SqueezeBertPreTrainedModel,
      )

else:
   import sys

   _snake_case             =     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



