






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__	(  UpperCAmelCase     ):

  '''simple docstring'''







  def  lowerCamelCase       (      self		:			Tuple							)						->	str:


         """simple docstring"""
         _UpperCAmelCase							=    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 		SCREAMING_SNAKE_CASE__	:

  '''simple docstring'''







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


         """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  lowerCamelCase       (      self		:			int							)						->	List[Any]:


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


         """simple docstring"""
         _UpperCAmelCase							=    MobileViTModel(config=lowerCamelCase							)
         model.to(lowerCamelCase							)
         model.eval()
         _UpperCAmelCase							=    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		:			Optional[int]       ,				lowerCamelCase		:			List[Any]       ,				lowerCamelCase		:			Tuple       ,				lowerCamelCase		:			Optional[int]       ,				lowerCamelCase		:			str							)						->	int:


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


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


         """simple docstring"""
         _UpperCAmelCase							=    self.num_labels
         _UpperCAmelCase							=    MobileViTForSemanticSegmentation(lowerCamelCase							)
         model.to(lowerCamelCase							)
         model.eval()
         _UpperCAmelCase							=    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,
             )       ,				)
         _UpperCAmelCase							=    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		:			Union[str, Any]							)						->	Tuple:


         """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 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase					,      UpperCAmelCase					,      unittest.TestCase     ):

  '''simple docstring'''







  _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		:			Optional[Any]							)						->	Optional[Any]:


         """simple docstring"""
         _UpperCAmelCase							=    MobileViTModelTester(self							)
         _UpperCAmelCase							=    MobileViTConfigTester(self       ,				config_class=lowerCamelCase       ,				has_text_modality=lowerCamelCase							)


  def  lowerCamelCase       (      self		:			List[Any]							)						->	int:


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


  @unittest.skip(reason="""MobileViT does not use inputs_embeds"""							)
  def  lowerCamelCase       (      self		:			Tuple							)						->	Tuple:


         """simple docstring"""
         pass


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


         """simple docstring"""
         pass


  @unittest.skip(reason="""MobileViT does not output attentions"""							)
  def  lowerCamelCase       (      self		:			int							)						->	Tuple:


         """simple docstring"""
         pass


  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	Optional[int]:


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

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


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


         """simple docstring"""
         pass


  def  lowerCamelCase       (      self		:			Union[str, Any]							)						->	Tuple:


         """simple docstring"""
         _UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase							)


  def  lowerCamelCase       (      self		:			List[str]							)						->	int:


         """simple docstring"""
         def check_hidden_states_output(lowerCamelCase		:			Union[str, Any]       ,				lowerCamelCase		:			Dict       ,				lowerCamelCase		:			str							):
                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                model.to(lowerCamelCase							)
                model.eval()

                with torch.no_grad():
                       _UpperCAmelCase							=    model(**self._prepare_for_class(lowerCamelCase       ,				lowerCamelCase							)							)

                _UpperCAmelCase							=    outputs.hidden_states

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

         _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(lowerCamelCase       ,				lowerCamelCase       ,				lowerCamelCase							)

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

                check_hidden_states_output(lowerCamelCase       ,				lowerCamelCase       ,				lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Tuple							)						->	int:


         """simple docstring"""
         _UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowerCamelCase							)


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


         """simple docstring"""
         _UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase							)





  @slow
  def  lowerCamelCase       (      self		:			List[Any]							)						->	Optional[Any]:


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




def       _SCREAMING_SNAKE_CASE (							)				->						Dict:
       _UpperCAmelCase							=    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
       return image





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

  '''simple docstring'''







  @cached_property
  def  lowerCamelCase       (      self		:			List[str]							)						->	List[Any]:


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


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


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

         _UpperCAmelCase							=    self.default_image_processor
         _UpperCAmelCase							=    prepare_img()
         _UpperCAmelCase							=    image_processor(images=lowerCamelCase       ,				return_tensors="""pt"""							).to(lowerCamelCase							)

         # forward pass
         with torch.no_grad():
                _UpperCAmelCase							=    model(**lowerCamelCase							)

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

         _UpperCAmelCase							=    torch.tensor([-1.9364, -1.2327, -0.4653]							).to(lowerCamelCase							)

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


  @slow
  def  lowerCamelCase       (      self		:			Dict							)						->	Dict:


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

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

         _UpperCAmelCase							=    prepare_img()
         _UpperCAmelCase							=    image_processor(images=lowerCamelCase       ,				return_tensors="""pt"""							).to(lowerCamelCase							)

         # forward pass
         with torch.no_grad():
                _UpperCAmelCase							=    model(**lowerCamelCase							)
         _UpperCAmelCase							=    outputs.logits

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

         _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=lowerCamelCase       ,				)

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





  @slow
  def  lowerCamelCase       (      self		:			List[str]							)						->	Union[str, Any]:


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

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

         _UpperCAmelCase							=    prepare_img()
         _UpperCAmelCase							=    image_processor(images=lowerCamelCase       ,				return_tensors="""pt"""							).to(lowerCamelCase							)

         # forward pass
         with torch.no_grad():
                _UpperCAmelCase							=    model(**lowerCamelCase							)

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

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

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







def       _SCREAMING_SNAKE_CASE    (			__lowercase :      int     )    ->   list[int]:





    """simple docstring"""

    if length <= 0 or not isinstance(__lowercase      ,					__lowercase     ):
        raise ValueError("""Length must be a positive integer."""     )
    return [n * (2 * n - 1) for n in range(__lowercase     )]


if __name__ == "__main__":
  print(hexagonal_numbers(length=5))
  print(hexagonal_numbers(length=10))




