

"""simple docstring"""

import os
import unittest

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    BertTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english






@require_tokenizers
class 			__a					(						__magic_name__       ,	unittest.TestCase       ):





       """simple docstring"""


       __UpperCamelCase					:      Optional[Any]    =						BertTokenizer
       __UpperCamelCase					:      int    =						BertTokenizerFast
       __UpperCamelCase					:      Optional[Any]    =						True
       __UpperCamelCase					:      str    =						True
       __UpperCamelCase					:      Optional[int]    =						filter_non_english






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        super().setUp()

        lowerCAmelCase__   :				str 			=				[
            "[UNK]",
            "[CLS]",
            "[SEP]",
            "[PAD]",
            "[MASK]",
            "want",
            "##want",
            "##ed",
            "wa",
            "un",
            "runn",
            "##ing",
            ",",
            "low",
            "lowest",
        ]
        lowerCAmelCase__   :				Optional[int] 			=				os.path.join(self.tmpdirname			,					VOCAB_FILES_NAMES["vocab_file"]   )
        with open(self.vocab_file			,					"w"			,					encoding="utf-8"   ) as vocab_writer:
         vocab_writer.write("".join([x + "\n" for x in vocab_tokens]   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				"UNwant\u00E9d,running"
        lowerCAmelCase__   :				Optional[int] 			=				"unwanted, running"
        return input_text, output_text






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				self.tokenizer_class(self.vocab_file   )

        lowerCAmelCase__   :				List[Any] 			=				tokenizer.tokenize("UNwant\u00E9d,running"   )
        self.assertListEqual(snake_case			,					["un", "##want", "##ed", ",", "runn", "##ing"]   )
        self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case   )			,					[9, 6, 7, 12, 10, 11]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        if not self.test_rust_tokenizer:
         return

        lowerCAmelCase__   :				Union[str, Any] 			=				self.get_tokenizer()
        lowerCAmelCase__   :				str 			=				self.get_rust_tokenizer()

        lowerCAmelCase__   :				Optional[int] 			=				"UNwant\u00E9d,running"

        lowerCAmelCase__   :				Dict 			=				tokenizer.tokenize(snake_case   )
        lowerCAmelCase__   :				str 			=				rust_tokenizer.tokenize(snake_case   )
        self.assertListEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				tokenizer.encode(snake_case			,					add_special_tokens=snake_case   )
        lowerCAmelCase__   :				Tuple 			=				rust_tokenizer.encode(snake_case			,					add_special_tokens=snake_case   )
        self.assertListEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				Tuple 			=				self.get_rust_tokenizer()
        lowerCAmelCase__   :				Tuple 			=				tokenizer.encode(snake_case   )
        lowerCAmelCase__   :				Optional[Any] 			=				rust_tokenizer.encode(snake_case   )
        self.assertListEqual(snake_case			,					snake_case   )

        # With lower casing
        lowerCAmelCase__   :				List[str] 			=				self.get_tokenizer(do_lower_case=snake_case   )
        lowerCAmelCase__   :				Any 			=				self.get_rust_tokenizer(do_lower_case=snake_case   )

        lowerCAmelCase__   :				Any 			=				"UNwant\u00E9d,running"

        lowerCAmelCase__   :				str 			=				tokenizer.tokenize(snake_case   )
        lowerCAmelCase__   :				Optional[Any] 			=				rust_tokenizer.tokenize(snake_case   )
        self.assertListEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				List[Any] 			=				tokenizer.encode(snake_case			,					add_special_tokens=snake_case   )
        lowerCAmelCase__   :				Union[str, Any] 			=				rust_tokenizer.encode(snake_case			,					add_special_tokens=snake_case   )
        self.assertListEqual(snake_case			,					snake_case   )

        lowerCAmelCase__   :				Optional[int] 			=				self.get_rust_tokenizer()
        lowerCAmelCase__   :				int 			=				tokenizer.encode(snake_case   )
        lowerCAmelCase__   :				Any 			=				rust_tokenizer.encode(snake_case   )
        self.assertListEqual(snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[int] 			=				BasicTokenizer()

        self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"   )			,					["ah", "\u535A", "\u63A8", "zz"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				BasicTokenizer(do_lower_case=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  "   )			,					["hello", "!", "how", "are", "you", "?"]   )
        self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )			,					["hello"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				BasicTokenizer(do_lower_case=snake_case			,					strip_accents=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )			,					["hällo", "!", "how", "are", "you", "?"]   )
        self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )			,					["h\u00E9llo"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[int] 			=				BasicTokenizer(do_lower_case=snake_case			,					strip_accents=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )			,					["hallo", "!", "how", "are", "you", "?"]   )
        self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )			,					["hello"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				BasicTokenizer(do_lower_case=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )			,					["hallo", "!", "how", "are", "you", "?"]   )
        self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )			,					["hello"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				BasicTokenizer(do_lower_case=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  "   )			,					["HeLLo", "!", "how", "Are", "yoU", "?"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				BasicTokenizer(do_lower_case=snake_case			,					strip_accents=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )			,					["HäLLo", "!", "how", "Are", "yoU", "?"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				BasicTokenizer(do_lower_case=snake_case			,					strip_accents=snake_case   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )			,					["HaLLo", "!", "how", "Are", "yoU", "?"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Dict 			=				BasicTokenizer(do_lower_case=snake_case			,					never_split=["[UNK]"]   )

        self.assertListEqual(
            tokenizer.tokenize(" \tHeLLo!how  \n Are yoU? [UNK]"   )			,					["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				BasicTokenizer()
        lowerCAmelCase__   :				Optional[int] 			=				"a\n'll !!to?'d of, can't."
        lowerCAmelCase__   :				Dict 			=				["a", "'", "ll", "!", "!", "to", "?", "'", "d", "of", ",", "can", "'", "t", "."]
        self.assertListEqual(tokenizer.tokenize(snake_case   )			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]

        lowerCAmelCase__   :				List[str] 			=				{}
        for i, token in enumerate(snake_case   ):
         lowerCAmelCase__   :				Any 			=				i
        lowerCAmelCase__   :				str 			=				WordpieceTokenizer(vocab=snake_case			,					unk_token="[UNK]"   )

        self.assertListEqual(tokenizer.tokenize(""   )			,					[]   )

        self.assertListEqual(tokenizer.tokenize("unwanted running"   )			,					["un", "##want", "##ed", "runn", "##ing"]   )

        self.assertListEqual(tokenizer.tokenize("unwantedX running"   )			,					["[UNK]", "runn", "##ing"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        self.assertTrue(_is_whitespace(" "   )   )
        self.assertTrue(_is_whitespace("\t"   )   )
        self.assertTrue(_is_whitespace("\r"   )   )
        self.assertTrue(_is_whitespace("\n"   )   )
        self.assertTrue(_is_whitespace("\u00A0"   )   )

        self.assertFalse(_is_whitespace("A"   )   )
        self.assertFalse(_is_whitespace("-"   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        self.assertTrue(_is_control("\u0005"   )   )

        self.assertFalse(_is_control("A"   )   )
        self.assertFalse(_is_control(" "   )   )
        self.assertFalse(_is_control("\t"   )   )
        self.assertFalse(_is_control("\r"   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        self.assertTrue(_is_punctuation("-"   )   )
        self.assertTrue(_is_punctuation("$"   )   )
        self.assertTrue(_is_punctuation("`"   )   )
        self.assertTrue(_is_punctuation("."   )   )

        self.assertFalse(_is_punctuation("A"   )   )
        self.assertFalse(_is_punctuation(" "   )   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				self.get_tokenizer()
        lowerCAmelCase__   :				Optional[int] 			=				self.get_rust_tokenizer()

        # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
        self.assertListEqual([tokenizer.tokenize(snake_case   ) for t in ["Test", "\xad", "test"]]			,					[["[UNK]"], [], ["[UNK]"]]   )

        self.assertListEqual(
            [rust_tokenizer.tokenize(snake_case   ) for t in ["Test", "\xad", "test"]]			,					[["[UNK]"], [], ["[UNK]"]]   )






       @slow
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[Any] 			=				self.tokenizer_class.from_pretrained("bert-base-uncased"   )

        lowerCAmelCase__   :				List[str] 			=				tokenizer.encode("sequence builders"			,					add_special_tokens=snake_case   )
        lowerCAmelCase__   :				str 			=				tokenizer.encode("multi-sequence build"			,					add_special_tokens=snake_case   )

        lowerCAmelCase__   :				Dict 			=				tokenizer.build_inputs_with_special_tokens(snake_case   )
        lowerCAmelCase__   :				Any 			=				tokenizer.build_inputs_with_special_tokens(snake_case			,					snake_case   )

        assert encoded_sentence == [101] + text + [102]
        assert encoded_pair == [101] + text + [102] + text_a + [102]






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""   ):
          lowerCAmelCase__   :				Any 			=				self.rust_tokenizer_class.from_pretrained(snake_case			,					**snake_case   )

          lowerCAmelCase__   :				str 			=				F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
          lowerCAmelCase__   :				List[Any] 			=				tokenizer_r.encode_plus(
              snake_case			,					return_attention_mask=snake_case			,					return_token_type_ids=snake_case			,					return_offsets_mapping=snake_case			,					add_special_tokens=snake_case			,					)

          lowerCAmelCase__   :				Dict 			=				tokenizer_r.do_lower_case if hasattr(snake_case			,					"do_lower_case"   ) else False
          lowerCAmelCase__   :				str 			=				(
              [
                  ((0, 0), tokenizer_r.cls_token),
                  ((0, 1), "A"),
                  ((1, 2), ","),
                  ((3, 5), "na"),
                  ((5, 6), "##ï"),
                  ((6, 8), "##ve"),
                  ((9, 15), tokenizer_r.mask_token),
                  ((16, 21), "Allen"),
                  ((21, 23), "##NL"),
                  ((23, 24), "##P"),
                  ((25, 33), "sentence"),
                  ((33, 34), "."),
                  ((0, 0), tokenizer_r.sep_token),
              ]
              if not do_lower_case
              else [
                  ((0, 0), tokenizer_r.cls_token),
                  ((0, 1), "a"),
                  ((1, 2), ","),
                  ((3, 8), "naive"),
                  ((9, 15), tokenizer_r.mask_token),
                  ((16, 21), "allen"),
                  ((21, 23), "##nl"),
                  ((23, 24), "##p"),
                  ((25, 33), "sentence"),
                  ((33, 34), "."),
                  ((0, 0), tokenizer_r.sep_token),
              ]
          )

          self.assertEqual(
              [e[1] for e in expected_results]			,					tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]   )   )
          self.assertEqual([e[0] for e in expected_results]			,					tokens["offset_mapping"]   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				["的", "人", "有"]
        lowerCAmelCase__   :				Optional[int] 			=				"".join(snake_case   )
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""   ):
          lowerCAmelCase__   :				List[Any] 			=				True
          lowerCAmelCase__   :				int 			=				self.tokenizer_class.from_pretrained(snake_case			,					**snake_case   )
          lowerCAmelCase__   :				Optional[int] 			=				self.rust_tokenizer_class.from_pretrained(snake_case			,					**snake_case   )

          lowerCAmelCase__   :				List[Any] 			=				tokenizer_p.encode(snake_case			,					add_special_tokens=snake_case   )
          lowerCAmelCase__   :				Any 			=				tokenizer_r.encode(snake_case			,					add_special_tokens=snake_case   )

          lowerCAmelCase__   :				Dict 			=				tokenizer_r.convert_ids_to_tokens(snake_case   )
          lowerCAmelCase__   :				List[str] 			=				tokenizer_p.convert_ids_to_tokens(snake_case   )

          # it is expected that each Chinese character is not preceded by "##"
          self.assertListEqual(snake_case			,					snake_case   )
          self.assertListEqual(snake_case			,					snake_case   )

          lowerCAmelCase__   :				Union[str, Any] 			=				False
          lowerCAmelCase__   :				Tuple 			=				self.rust_tokenizer_class.from_pretrained(snake_case			,					**snake_case   )
          lowerCAmelCase__   :				Tuple 			=				self.tokenizer_class.from_pretrained(snake_case			,					**snake_case   )

          lowerCAmelCase__   :				List[str] 			=				tokenizer_r.encode(snake_case			,					add_special_tokens=snake_case   )
          lowerCAmelCase__   :				List[Any] 			=				tokenizer_p.encode(snake_case			,					add_special_tokens=snake_case   )

          lowerCAmelCase__   :				Optional[Any] 			=				tokenizer_r.convert_ids_to_tokens(snake_case   )
          lowerCAmelCase__   :				Optional[int] 			=				tokenizer_p.convert_ids_to_tokens(snake_case   )

          # it is expected that only the first Chinese character is not preceded by "##".
          lowerCAmelCase__   :				str 			=				[
              F"""##{token}""" if idx != 0 else token for idx, token in enumerate(snake_case   )
          ]
          self.assertListEqual(snake_case			,					snake_case   )
          self.assertListEqual(snake_case			,					snake_case   )









"""simple docstring"""

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





       """simple docstring"""


       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				self.config_class(**self.inputs_dict   )
        self.parent.assertTrue(hasattr(snake_case			,					"width_multiplier"   )   )






class 			__a					:





       """simple docstring"""


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





        """simple docstring"""

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

        lowerCAmelCase__   :				int 			=				self.get_config()

        return config, pixel_values, labels, pixel_labels






       def 			SCREAMING_SNAKE_CASE_	(   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 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Any 			=				MobileViTVaModel(config=snake_case   )
        model.to(snake_case   )
        model.eval()
        lowerCAmelCase__   :				int 			=				model(snake_case   )
        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 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

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






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				self.num_labels
        lowerCAmelCase__   :				Optional[int] 			=				MobileViTVaForSemanticSegmentation(snake_case   )
        model.to(snake_case   )
        model.eval()
        lowerCAmelCase__   :				Any 			=				model(snake_case   )
        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__   :				Tuple 			=				model(snake_case			,					labels=snake_case   )
        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 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				int 			=				self.prepare_config_and_inputs()
        lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__   :				Any 			=				config_and_inputs
        lowerCAmelCase__   :				int 			=				{"pixel_values": pixel_values}
        return config, inputs_dict






@require_torch
class 			__a					(						__magic_name__       ,	__magic_name__       ,	unittest.TestCase       ):





       """simple docstring"""


       __UpperCamelCase					:      List[Any]    =						(
           (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )

       __UpperCamelCase					:      List[Any]    =						(
           {
               'feature-extraction': MobileViTVaModel,
               'image-classification': MobileViTVaForImageClassification,
               'image-segmentation': MobileViTVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       __UpperCamelCase					:      str    =						False
       __UpperCamelCase					:      int    =						False
       __UpperCamelCase					:      Tuple    =						False
       __UpperCamelCase					:      List[str]    =						False






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				MobileViTVaModelTester(self   )
        lowerCAmelCase__   :				List[str] 			=				MobileViTVaConfigTester(self			,					config_class=snake_case			,					has_text_modality=snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        self.config_tester.run_common_tests()






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





        """simple docstring"""

        pass






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





        """simple docstring"""

        pass






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





        """simple docstring"""

        pass






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





        """simple docstring"""

        pass






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





        """simple docstring"""

        pass






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__			,						lowerCAmelCase__   :				Tuple 			=				self.model_tester.prepare_config_and_inputs_for_common()

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

         lowerCAmelCase__   :				Dict 			=				["pixel_values"]
         self.assertListEqual(arg_names[:1]			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        def check_hidden_states_output(snake_case			,					snake_case			,					snake_case   ):
         lowerCAmelCase__   :				List[str] 			=				model_class(snake_case   )
         model.to(snake_case   )
         model.eval()

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

         lowerCAmelCase__   :				str 			=				outputs.hidden_states

         lowerCAmelCase__   :				List[Any] 			=				5
         self.assertEqual(len(snake_case   )			,					snake_case   )

         # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
         # with the width and height being successively divided by 2.
         lowerCAmelCase__   :				str 			=				2
         for i in range(len(snake_case   )   ):
          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__   :				Tuple 			=				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         lowerCAmelCase__   :				int 			=				True
         check_hidden_states_output(snake_case			,					snake_case			,					snake_case   )

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

         check_hidden_states_output(snake_case			,					snake_case			,					snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				str 			=				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*snake_case   )






       @slow
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__   :				Dict 			=				MobileViTVaModel.from_pretrained(snake_case   )
         self.assertIsNotNone(snake_case   )




def       SCREAMING_SNAKE_CASE							( )			->						Optional[int]:
 lowerCAmelCase__   :				Optional[Any] 			=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
 return image






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





       """simple docstring"""


       @cached_property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

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






       @slow
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Dict 			=				MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"   ).to(
            snake_case   )

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

        # forward pass
        with torch.no_grad():
         lowerCAmelCase__   :				str 			=				model(**snake_case   )

        # verify the logits
        lowerCAmelCase__   :				int 			=				torch.Size((1, 1_000)   )
        self.assertEqual(outputs.logits.shape			,					snake_case   )

        lowerCAmelCase__   :				Optional[int] 			=				torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]   ).to(snake_case   )

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






       @slow
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"   )
        lowerCAmelCase__   :				Tuple 			=				model.to(snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"   )

        lowerCAmelCase__   :				Union[str, Any] 			=				prepare_img()
        lowerCAmelCase__   :				str 			=				image_processor(images=snake_case			,					return_tensors="pt"   ).to(snake_case   )

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

        # verify the logits
        lowerCAmelCase__   :				Tuple 			=				torch.Size((1, 21, 32, 32)   )
        self.assertEqual(logits.shape			,					snake_case   )

        lowerCAmelCase__   :				Dict 			=				torch.tensor(
            [
                [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
                [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
                [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
            ]			,					device=snake_case			,					)

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






       @slow
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[int] 			=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"   )
        lowerCAmelCase__   :				List[Any] 			=				model.to(snake_case   )

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

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

        # forward pass
        with torch.no_grad():
         lowerCAmelCase__   :				Union[str, Any] 			=				model(**snake_case   )

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

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

        lowerCAmelCase__   :				Any 			=				image_processor.post_process_semantic_segmentation(outputs=snake_case   )
        lowerCAmelCase__   :				Optional[int] 			=				torch.Size((32, 32)   )
        self.assertEqual(segmentation[0].shape			,					snake_case   )






