



'''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 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  def 							UpperCAmelCase_     (   self				)   ->		Optional[Any]:
      lowerCAmelCase__			:  Tuple											= 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 	lowerCAmelCase_:
  '''simple docstring'''




  def __init__(   self  ,__UpperCAmelCase  ,__UpperCAmelCase=13  ,__UpperCAmelCase=32  ,__UpperCAmelCase=2  ,__UpperCAmelCase=3  ,__UpperCAmelCase=640  ,__UpperCAmelCase=4  ,__UpperCAmelCase="silu"  ,__UpperCAmelCase=3  ,__UpperCAmelCase=32  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=10  ,__UpperCAmelCase=None  ,)   ->		Any:
      lowerCAmelCase__			:  str											= parent
      lowerCAmelCase__			:  Any											= batch_size
      lowerCAmelCase__			:  Union[str, Any]											= image_size
      lowerCAmelCase__			:  str											= patch_size
      lowerCAmelCase__			:  Optional[Any]											= num_channels
      lowerCAmelCase__			:  Union[str, Any]											= last_hidden_size
      lowerCAmelCase__			:  Dict											= num_attention_heads
      lowerCAmelCase__			:  Optional[Any]											= hidden_act
      lowerCAmelCase__			:  List[str]											= conv_kernel_size
      lowerCAmelCase__			:  Tuple											= output_stride
      lowerCAmelCase__			:  str											= hidden_dropout_prob
      lowerCAmelCase__			:  int											= attention_probs_dropout_prob
      lowerCAmelCase__			:  Optional[Any]											= classifier_dropout_prob
      lowerCAmelCase__			:  Union[str, Any]											= use_labels
      lowerCAmelCase__			:  Any											= is_training
      lowerCAmelCase__			:  Optional[Any]											= num_labels
      lowerCAmelCase__			:  Union[str, Any]											= initializer_range
      lowerCAmelCase__			:  str											= scope




  def 							UpperCAmelCase_     (   self				)   ->		Any:
      lowerCAmelCase__			:  Optional[int]											= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

      lowerCAmelCase__			:  str											= None
      lowerCAmelCase__			:  Optional[Any]											= None
      if self.use_labels:
          lowerCAmelCase__			:  Optional[Any]											= ids_tensor([self.batch_size]  ,self.num_labels				)
          lowerCAmelCase__			:  Any											= ids_tensor([self.batch_size, self.image_size, self.image_size]  ,self.num_labels				)

      lowerCAmelCase__			:  str											= self.get_config()

      return config, pixel_values, labels, pixel_labels




  def 							UpperCAmelCase_     (   self				)   ->		str:
      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 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		int:
      lowerCAmelCase__			:  Optional[Any]											= MobileViTModel(config=__UpperCAmelCase				)
      model.to(__UpperCAmelCase				)
      model.eval()
      lowerCAmelCase__			:  Optional[int]											= 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 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Optional[Any]:
      lowerCAmelCase__			:  int											= self.num_labels
      lowerCAmelCase__			:  Any											= MobileViTForImageClassification(__UpperCAmelCase				)
      model.to(__UpperCAmelCase				)
      model.eval()
      lowerCAmelCase__			:  Dict											= model(__UpperCAmelCase  ,labels=__UpperCAmelCase				)
      self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.num_labels)				)




  def 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		int:
      lowerCAmelCase__			:  str											= self.num_labels
      lowerCAmelCase__			:  Dict											= MobileViTForSemanticSegmentation(__UpperCAmelCase				)
      model.to(__UpperCAmelCase				)
      model.eval()
      lowerCAmelCase__			:  Tuple											= 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,
          )  ,)
      lowerCAmelCase__			:  int											= 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 							UpperCAmelCase_     (   self				)   ->		Any:
      lowerCAmelCase__			:  Optional[Any]											= self.prepare_config_and_inputs()
      lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__			:  str											= config_and_inputs
      lowerCAmelCase__			:  Any											= {"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_torch
class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			unittest.TestCase					):
  '''simple docstring'''




  __lowercase							:				str           =				(
      (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  __lowercase							:				List[Any]           =				(
      {
          '''feature-extraction''': MobileViTModel,
          '''image-classification''': MobileViTForImageClassification,
          '''image-segmentation''': MobileViTForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  __lowercase							:				str           =				False
  __lowercase							:				Optional[Any]           =				False
  __lowercase							:				str           =				False
  __lowercase							:				Union[str, Any]           =				False




  def 							UpperCAmelCase_     (   self				)   ->		List[str]:
      lowerCAmelCase__			:  List[str]											= MobileViTModelTester(self				)
      lowerCAmelCase__			:  List[Any]											= MobileViTConfigTester(self  ,config_class=__UpperCAmelCase  ,has_text_modality=__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      self.config_tester.run_common_tests()




  @unittest.skip(reason="""MobileViT does not use inputs_embeds"""				)
  def 							UpperCAmelCase_     (   self				)   ->		Optional[Any]:
      pass




  @unittest.skip(reason="""MobileViT does not support input and output embeddings"""				)
  def 							UpperCAmelCase_     (   self				)   ->		str:
      pass




  @unittest.skip(reason="""MobileViT does not output attentions"""				)
  def 							UpperCAmelCase_     (   self				)   ->		Any:
      pass




  def 							UpperCAmelCase_     (   self				)   ->		Tuple:
      lowerCAmelCase__				,       lowerCAmelCase__			:  List[Any]											= self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          lowerCAmelCase__			:  str											= model_class(__UpperCAmelCase				)
          lowerCAmelCase__			:  Optional[Any]											= inspect.signature(model.forward				)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          lowerCAmelCase__			:  List[Any]											= [*signature.parameters.keys()]

          lowerCAmelCase__			:  str											= ["""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 							UpperCAmelCase_     (   self				)   ->		List[str]:
      pass




  def 							UpperCAmelCase_     (   self				)   ->		Optional[int]:
      lowerCAmelCase__			:  Tuple											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		int:
      def check_hidden_states_output(__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				):
          lowerCAmelCase__			:  Tuple											= model_class(__UpperCAmelCase				)
          model.to(__UpperCAmelCase				)
          model.eval()

          with torch.no_grad():
              lowerCAmelCase__			:  Optional[int]											= model(**self._prepare_for_class(__UpperCAmelCase  ,__UpperCAmelCase				)				)

          lowerCAmelCase__			:  str											= outputs.hidden_states

          lowerCAmelCase__			:  Optional[int]											= 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.
          lowerCAmelCase__			:  Any											= 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				)

      lowerCAmelCase__				,       lowerCAmelCase__			:  Optional[Any]											= self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          lowerCAmelCase__			:  Union[str, Any]											= True
          check_hidden_states_output(__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)

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

          check_hidden_states_output(__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		List[Any]:
      lowerCAmelCase__			:  Optional[int]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		str:
      lowerCAmelCase__			:  Tuple											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase				)






  @slow
  def 							UpperCAmelCase_     (   self				)   ->		str:
      for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase__			:  Dict											= MobileViTModel.from_pretrained(__UpperCAmelCase				)
          self.assertIsNotNone(__UpperCAmelCase				)







def        _SCREAMING_SNAKE_CASE  (	):



    """simple docstring"""





    lowerCAmelCase__			:  Dict											= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
    return image






@require_torch
@require_vision
class 	lowerCAmelCase_(    unittest.TestCase					):
  '''simple docstring'''




  @cached_property
  def 							UpperCAmelCase_     (   self				)   ->		Union[str, Any]:
      return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""				) if is_vision_available() else None




  @slow
  def 							UpperCAmelCase_     (   self				)   ->		List[str]:
      lowerCAmelCase__			:  int											= MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""				).to(__UpperCAmelCase				)

      lowerCAmelCase__			:  Optional[int]											= self.default_image_processor
      lowerCAmelCase__			:  int											= prepare_img()
      lowerCAmelCase__			:  Any											= image_processor(images=__UpperCAmelCase  ,return_tensors="""pt"""				).to(__UpperCAmelCase				)

      # forward pass
      with torch.no_grad():
          lowerCAmelCase__			:  Optional[int]											= model(**__UpperCAmelCase				)

      # verify the logits
      lowerCAmelCase__			:  Optional[Any]											= torch.Size((1, 1000)				)
      self.assertEqual(outputs.logits.shape  ,__UpperCAmelCase				)

      lowerCAmelCase__			:  str											= torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]				).to(__UpperCAmelCase				)

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




  @slow
  def 							UpperCAmelCase_     (   self				)   ->		List[Any]:
      lowerCAmelCase__			:  Any											= MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""				)
      lowerCAmelCase__			:  Union[str, Any]											= model.to(__UpperCAmelCase				)

      lowerCAmelCase__			:  Any											= MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""				)

      lowerCAmelCase__			:  Tuple											= prepare_img()
      lowerCAmelCase__			:  Any											= image_processor(images=__UpperCAmelCase  ,return_tensors="""pt"""				).to(__UpperCAmelCase				)

      # forward pass
      with torch.no_grad():
          lowerCAmelCase__			:  List[str]											= model(**__UpperCAmelCase				)
      lowerCAmelCase__			:  Optional[int]											= outputs.logits

      # verify the logits
      lowerCAmelCase__			:  Optional[Any]											= torch.Size((1, 21, 32, 32)				)
      self.assertEqual(logits.shape  ,__UpperCAmelCase				)

      lowerCAmelCase__			:  str											= torch.tensor(
          [
              [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
              [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
              [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
          ]  ,device=__UpperCAmelCase  ,)

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






  @slow
  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      lowerCAmelCase__			:  Dict											= MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""				)
      lowerCAmelCase__			:  Optional[int]											= model.to(__UpperCAmelCase				)

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

      lowerCAmelCase__			:  Dict											= prepare_img()
      lowerCAmelCase__			:  Any											= image_processor(images=__UpperCAmelCase  ,return_tensors="""pt"""				).to(__UpperCAmelCase				)

      # forward pass
      with torch.no_grad():
          lowerCAmelCase__			:  Tuple											= model(**__UpperCAmelCase				)

      lowerCAmelCase__			:  List[Any]											= outputs.logits.detach().cpu()

      lowerCAmelCase__			:  Optional[int]											= image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase  ,target_sizes=[(50, 60)]				)
      lowerCAmelCase__			:  str											= torch.Size((50, 60)				)
      self.assertEqual(segmentation[0].shape  ,__UpperCAmelCase				)

      lowerCAmelCase__			:  List[str]											= image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase				)
      lowerCAmelCase__			:  str											= torch.Size((32, 32)				)
      self.assertEqual(segmentation[0].shape  ,__UpperCAmelCase				)







'''simple docstring'''





from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_lowerCAmelCase										=     logging.get_logger(__name__)

_lowerCAmelCase										=     {
    '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''',
}






class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  __lowercase							:				Tuple           =				'''convnextv2'''




  def __init__(   self  ,__UpperCAmelCase=3  ,__UpperCAmelCase=4  ,__UpperCAmelCase=4  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=1E-12  ,__UpperCAmelCase=0.0  ,__UpperCAmelCase=224  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,**__UpperCAmelCase  ,)   ->		Union[str, Any]:
      super().__init__(**__UpperCAmelCase				)

      lowerCAmelCase__			:  int											= num_channels
      lowerCAmelCase__			:  List[Any]											= patch_size
      lowerCAmelCase__			:  Union[str, Any]											= num_stages
      lowerCAmelCase__			:  Tuple											= [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
      lowerCAmelCase__			:  str											= [3, 3, 9, 3] if depths is None else depths
      lowerCAmelCase__			:  Optional[Any]											= hidden_act
      lowerCAmelCase__			:  str											= initializer_range
      lowerCAmelCase__			:  List[str]											= layer_norm_eps
      lowerCAmelCase__			:  Dict											= drop_path_rate
      lowerCAmelCase__			:  int											= image_size
      lowerCAmelCase__			:  int											= ["""stem"""] + [F"""stage{idx}""" for idx in range(1  ,len(self.depths				) + 1				)]
      lowerCAmelCase__				,       lowerCAmelCase__			:  Tuple											= get_aligned_output_features_output_indices(
          out_features=__UpperCAmelCase  ,out_indices=__UpperCAmelCase  ,stage_names=self.stage_names				)


