





import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
      from transformers.models.mobilevitva.modeling_mobilevitva import (
          MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
          make_divisible,
      )


if is_vision_available():
      from PIL import Image

      from transformers import MobileViTImageProcessor



class       A__     ( _SCREAMING_SNAKE_CASE    ):





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[Any] 			=     self.config_class(**self.inputs_dict     )
       self.parent.assertTrue(hasattr(A_ ,							"width_multiplier"     )     )



class       A__     :





      def __init__(				self ,							A_ ,							A_=13 ,							A_=64 ,							A_=2 ,							A_=3 ,							A_="swish" ,							A_=3 ,							A_=32 ,							A_=0.1 ,							A_=0.02 ,							A_=True ,							A_=True ,							A_=10 ,							A_=None ,							A_=0.25 ,							A_=0.0 ,							A_=0.0 ,							):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     parent
       UpperCamelCase			:      Any 			=     batch_size
       UpperCamelCase			:      Optional[int] 			=     image_size
       UpperCamelCase			:      Any 			=     patch_size
       UpperCamelCase			:      Optional[Any] 			=     num_channels
       UpperCamelCase			:      str 			=     make_divisible(512 * width_multiplier ,							divisor=8     )
       UpperCamelCase			:      Dict 			=     hidden_act
       UpperCamelCase			:      int 			=     conv_kernel_size
       UpperCamelCase			:      Tuple 			=     output_stride
       UpperCamelCase			:      List[str] 			=     classifier_dropout_prob
       UpperCamelCase			:      Dict 			=     use_labels
       UpperCamelCase			:      Optional[Any] 			=     is_training
       UpperCamelCase			:      List[Any] 			=     num_labels
       UpperCamelCase			:      int 			=     initializer_range
       UpperCamelCase			:      Optional[Any] 			=     scope
       UpperCamelCase			:      Union[str, Any] 			=     width_multiplier
       UpperCamelCase			:      int 			=     ffn_dropout
       UpperCamelCase			:      Optional[Any] 			=     attn_dropout





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

       UpperCamelCase			:      int 			=     self.get_config()

       return config, pixel_values, labels, pixel_labels





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return MobileViTVaConfig(
           image_size=self.image_size ,							patch_size=self.patch_size ,							num_channels=self.num_channels ,							hidden_act=self.hidden_act ,							conv_kernel_size=self.conv_kernel_size ,							output_stride=self.output_stride ,							classifier_dropout_prob=self.classifier_dropout_prob ,							initializer_range=self.initializer_range ,							width_multiplier=self.width_multiplier ,							ffn_dropout=self.ffn_dropout_prob ,							attn_dropout=self.attn_dropout_prob ,							)





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     MobileViTVaModel(config=A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      List[Any] 			=     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  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     self.num_labels
       UpperCamelCase			:      int 			=     MobileViTVaForImageClassification(A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Any 			=     model(A_ ,							labels=A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.num_labels)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     self.num_labels
       UpperCamelCase			:      Optional[Any] 			=     MobileViTVaForSemanticSegmentation(A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Optional[Any] 			=     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,
           ) ,							)
       UpperCamelCase			:      Dict 			=     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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     self.prepare_config_and_inputs()
       UpperCamelCase			,					UpperCamelCase			,					UpperCamelCase			,					UpperCamelCase			:      Optional[Any] 			=     config_and_inputs
       UpperCamelCase			:      Optional[Any] 			=     {"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class       A__     ( _SCREAMING_SNAKE_CASE ,     _SCREAMING_SNAKE_CASE ,     unittest.TestCase    ):
      _UpperCAmelCase			:int							=     (
          (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
          if is_torch_available()
          else ()
      )

      _UpperCAmelCase			:Dict							=     (
          {
              "feature-extraction": MobileViTVaModel,
              "image-classification": MobileViTVaForImageClassification,
              "image-segmentation": MobileViTVaForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      _UpperCAmelCase			:str							=     False
      _UpperCAmelCase			:int							=     False
      _UpperCAmelCase			:Optional[int]							=     False
      _UpperCAmelCase			:Optional[Any]							=     False





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     MobileViTVaModelTester(self     )
       UpperCamelCase			:      List[str] 			=     MobileViTVaConfigTester(self ,							config_class=A_ ,							has_text_modality=A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @unittest.skip(reason="MobileViTV2 does not output attentions"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @require_torch_multi_gpu
      @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





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




       pass





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Any 			=     self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase			:      Optional[int] 			=     ["pixel_values"]
        self.assertListEqual(arg_names[:1] ,							A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       def check_hidden_states_output(A_ ,							A_ ,							A_     ):
        UpperCamelCase			:      Optional[Any] 			=     model_class(A_     )
        model.to(A_     )
        model.eval()

        with torch.no_grad():
         UpperCamelCase			:      List[Any] 			=     model(**self._prepare_for_class(A_ ,							A_     )     )

        UpperCamelCase			:      List[Any] 			=     outputs.hidden_states

        UpperCamelCase			:      int 			=     5
        self.assertEqual(len(A_     ) ,							A_     )

        # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        UpperCamelCase			:      Dict 			=     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     )

       UpperCamelCase			,					UpperCamelCase			:      List[Any] 			=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase			:      List[str] 			=     True
        check_hidden_states_output(A_ ,							A_ ,							A_     )

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

        check_hidden_states_output(A_ ,							A_ ,							A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*A_     )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase			:      Any 			=     MobileViTVaModel.from_pretrained(A_     )
        self.assertIsNotNone(A_     )



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



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





      @cached_property
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return (
           MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"     )
           if is_vision_available()
           else None
       )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"     ).to(
           A_     )

       UpperCamelCase			:      Union[str, Any] 			=     self.default_image_processor
       UpperCamelCase			:      Union[str, Any] 			=     prepare_img()
       UpperCamelCase			:      Union[str, Any] 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

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

       # verify the logits
       UpperCamelCase			:      int 			=     torch.Size((1, 1000)     )
       self.assertEqual(outputs.logits.shape ,							A_     )

       UpperCamelCase			:      List[str] 			=     torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]     ).to(A_     )

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





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"     )
       UpperCamelCase			:      Union[str, Any] 			=     model.to(A_     )

       UpperCamelCase			:      str 			=     MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"     )

       UpperCamelCase			:      int 			=     prepare_img()
       UpperCamelCase			:      Optional[int] 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      List[str] 			=     model(**A_     )
       UpperCamelCase			:      Tuple 			=     outputs.logits

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

       UpperCamelCase			:      Tuple 			=     torch.tensor(
           [
               [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
               [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
               [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
           ] ,							device=A_ ,							)

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





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"     )
       UpperCamelCase			:      Dict 			=     model.to(A_     )

       UpperCamelCase			:      List[str] 			=     MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"     )

       UpperCamelCase			:      Optional[int] 			=     prepare_img()
       UpperCamelCase			:      List[Any] 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      List[str] 			=     model(**A_     )

       UpperCamelCase			:      Optional[int] 			=     outputs.logits.detach().cpu()

       UpperCamelCase			:      Any 			=     image_processor.post_process_semantic_segmentation(outputs=A_ ,							target_sizes=[(50, 60)]     )
       UpperCamelCase			:      Union[str, Any] 			=     torch.Size((50, 60)     )
       self.assertEqual(segmentation[0].shape ,							A_     )

       UpperCamelCase			:      Optional[Any] 			=     image_processor.post_process_semantic_segmentation(outputs=A_     )
       UpperCamelCase			:      Tuple 			=     torch.Size((32, 32)     )
       self.assertEqual(segmentation[0].shape ,							A_     )







from typing import List, Optional

from tokenizers import ByteLevelBPETokenizer

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_blenderbot_small import BlenderbotSmallTokenizer


__lowerCamelCase :  Dict										=  logging.get_logger(__name__)

__lowerCamelCase :  Union[str, Any]										=  {
    """vocab_file""": """vocab.json""",
    """merges_file""": """merges.txt""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

__lowerCamelCase :  Dict										=  {
    """vocab_file""": {
        """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json"""
    },
    """merges_file""": {
        """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt"""
    },
    """tokenizer_config_file""": {
        """facebook/blenderbot_small-90M""": (
            """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json"""
        )
    },
}

__lowerCamelCase :  Tuple										=  {
    """facebook/blenderbot_small-90M""": 512,
}



class       A__     ( __snake_case    ):
      _UpperCAmelCase			:Union[str, Any]							=     VOCAB_FILES_NAMES
      _UpperCAmelCase			:Dict							=     PRETRAINED_VOCAB_FILES_MAP
      _UpperCAmelCase			:List[Any]							=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _UpperCAmelCase			:Optional[Any]							=     BlenderbotSmallTokenizer





      def __init__(				self ,							A_=None ,							A_=None ,							A_="<|endoftext|>" ,							A_="<|endoftext|>" ,							A_="<|endoftext|>" ,							A_=False ,							A_=True ,							**A_ ,							):
       '''simple docstring'''




       super().__init__(
           ByteLevelBPETokenizer(
               vocab=A_ ,							merges=A_ ,							add_prefix_space=A_ ,							trim_offsets=A_ ,							) ,							bos_token=A_ ,							eos_token=A_ ,							unk_token=A_ ,							**A_ ,							)
       UpperCamelCase			:      Union[str, Any] 			=     add_prefix_space





      def  __UpperCamelCase(				self ,							A_ ,							A_=None     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     [self.bos_token_id] + token_ids_a + [self.eos_token_id]
       if token_ids_a is None:
        return output

       return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]





      def  __UpperCamelCase(				self ,							A_ ,							A_ = None     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     [self.sep_token_id]
       UpperCamelCase			:      int 			=     [self.cls_token_id]

       if token_ids_a is None:
        return len(cls + token_ids_a + sep     ) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep     ) * [0]
