




'''simple docstring'''







from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_lowerCamelCase				:		Union[str, Any]				      =    logging.get_logger(__name__)

_lowerCamelCase				:		Union[str, Any]				      =    {
    'apple/mobilevit-small': 'https://huggingface.co/apple/mobilevit-small/resolve/main/config.json',
    'apple/mobilevit-x-small': 'https://huggingface.co/apple/mobilevit-x-small/resolve/main/config.json',
    'apple/mobilevit-xx-small': 'https://huggingface.co/apple/mobilevit-xx-small/resolve/main/config.json',
    'apple/deeplabv3-mobilevit-small': (
        'https://huggingface.co/apple/deeplabv3-mobilevit-small/resolve/main/config.json'
    ),
    'apple/deeplabv3-mobilevit-x-small': (
        'https://huggingface.co/apple/deeplabv3-mobilevit-x-small/resolve/main/config.json'
    ),
    'apple/deeplabv3-mobilevit-xx-small': (
        'https://huggingface.co/apple/deeplabv3-mobilevit-xx-small/resolve/main/config.json'
    ),
    # See all MobileViT models at https://huggingface.co/models?filter=mobilevit
}





class 	lowerCamelCase_				(			snake_case_				):




					'''simple docstring'''






					lowercase__       =					"""mobilevit"""






					def __init__(       self,    __UpperCamelCase=3,    __UpperCamelCase=256,    __UpperCamelCase=2,    __UpperCamelCase=[144, 192, 240],    __UpperCamelCase=[16, 32, 64, 96, 128, 160, 640],    __UpperCamelCase=4,    __UpperCamelCase=2.0,    __UpperCamelCase=4.0,    __UpperCamelCase="silu",    __UpperCamelCase=3,    __UpperCamelCase=32,    __UpperCamelCase=0.1,    __UpperCamelCase=0.0,    __UpperCamelCase=0.1,    __UpperCamelCase=0.02,    __UpperCamelCase=1E-5,    __UpperCamelCase=True,    __UpperCamelCase=256,    __UpperCamelCase=[6, 12, 18],    __UpperCamelCase=0.1,    __UpperCamelCase=255,    **__UpperCamelCase,    ):
							super().__init__(**_lowerCAmelCase					)

							_snake_case      			=			num_channels
							_snake_case      			=			image_size
							_snake_case      			=			patch_size
							_snake_case      			=			hidden_sizes
							_snake_case      			=			neck_hidden_sizes
							_snake_case      			=			num_attention_heads
							_snake_case      			=			mlp_ratio
							_snake_case      			=			expand_ratio
							_snake_case      			=			hidden_act
							_snake_case      			=			conv_kernel_size
							_snake_case      			=			output_stride
							_snake_case      			=			hidden_dropout_prob
							_snake_case      			=			attention_probs_dropout_prob
							_snake_case      			=			classifier_dropout_prob
							_snake_case      			=			initializer_range
							_snake_case      			=			layer_norm_eps
							_snake_case      			=			qkv_bias

							# decode head attributes for semantic segmentation
							_snake_case      			=			aspp_out_channels
							_snake_case      			=			atrous_rates
							_snake_case      			=			aspp_dropout_prob
							_snake_case      			=			semantic_loss_ignore_index





class 	lowerCamelCase_				(			snake_case_				):




					'''simple docstring'''






					lowercase__       =					version.parse("""1.11"""				)






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return OrderedDict([("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"})]					)






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							if self.task == "image-classification":
									return OrderedDict([("logits", {0: "batch"})]					)
							else:
									return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})]					)






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return 1E-4










import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class 		UpperCAmelCase    (    snake_case_							,unittest.TestCase					):
   SCREAMING_SNAKE_CASE__					      =  PreTrainedTokenizerFast
   SCREAMING_SNAKE_CASE__					      =  False
   SCREAMING_SNAKE_CASE__					      =  True
   SCREAMING_SNAKE_CASE__					      =  '''tokenizer_file'''





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	False  # because we don't have pretrained_vocab_files_map
         super().setUp()
         _lowerCAmelCase			      =	True

         _lowerCAmelCase			      =	['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
         _lowerCAmelCase			      =	'''SaulLu/dummy-tokenizer-bytelevel-bpe'''

         # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
         _lowerCAmelCase			      =	[(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

         _lowerCAmelCase			      =	PreTrainedTokenizerFast.from_pretrained(model_paths[0]      )
         tokenizer.save_pretrained(self.tmpdirname      )





   def 						__lowerCAmelCase				(						self      ):
         # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
         # model
         pass





   def 						__lowerCAmelCase				(						self      ):
         # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
         # model
         pass





   def 						__lowerCAmelCase				(						self      ):
         # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
         # model
         pass





   def 						__lowerCAmelCase				(						self      ):
         # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
         pass





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	self.tmpdirname
         # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''      ):
                     try:
                           _lowerCAmelCase			      =	tempfile.mkdtemp()
                           _lowerCAmelCase			      =	self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase							,  **_lowerCAmelCase      )

                           tokenizer.save_pretrained(self.tmpdirname      )
                           super().test_training_new_tokenizer()
                     finally:
                           # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                           # is restored
                           shutil.rmtree(self.tmpdirname      )
                           _lowerCAmelCase			      =	tmpdirname_orig





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	self.tmpdirname
         # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''      ):
                     try:
                           _lowerCAmelCase			      =	tempfile.mkdtemp()
                           _lowerCAmelCase			      =	self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase							,  **_lowerCAmelCase      )

                           tokenizer.save_pretrained(self.tmpdirname      )
                           super().test_training_new_tokenizer_with_special_tokens_change()
                     finally:
                           # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                           # is restored
                           shutil.rmtree(self.tmpdirname      )
                           _lowerCAmelCase			      =	tmpdirname_orig





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name      )

         _lowerCAmelCase			      =	('''a''' for _ in range(1_000      ))
         _lowerCAmelCase			      =	tokenizer.train_new_from_iterator(text_iterator=_lowerCAmelCase							,  length=1_000							,  vocab_size=50      )

         _lowerCAmelCase			      =	new_tokenizer.encode('''a🤗'''      )
         self.assertEqual(_lowerCAmelCase							,  [64, 172, 253, 97, 245]      )






@require_tokenizers
class 		UpperCAmelCase    (    unittest.TestCase					):





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	AutoTokenizer.from_pretrained('''bert-base-cased'''      )
         _lowerCAmelCase			      =	json.loads(tokenizer._tokenizer.to_str()      )
         _lowerCAmelCase			      =	len(_lowerCAmelCase      )

         with tempfile.TemporaryDirectory() as tmp_dir:
               # Hack to save this in the tokenizer_config.json
               _lowerCAmelCase			      =	['''tokenizer.4.0.0.json''']
               tokenizer.save_pretrained(_lowerCAmelCase      )
               json.dump(_lowerCAmelCase							,  open(os.path.join(_lowerCAmelCase							,  '''tokenizer.4.0.0.json'''      )							,  '''w'''      )      )

               # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
               _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
               self.assertEqual(len(_lowerCAmelCase      )							,  len(_lowerCAmelCase      ) + 1      )
               _lowerCAmelCase			      =	json.loads(new_tokenizer._tokenizer.to_str()      )
               self.assertIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )

               # Will need to be adjusted if we reach v42 and this test is still here.
               # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
               shutil.move(os.path.join(_lowerCAmelCase							,  '''tokenizer.4.0.0.json'''      )							,  os.path.join(_lowerCAmelCase							,  '''tokenizer.42.0.0.json'''      )      )
               _lowerCAmelCase			      =	['''tokenizer.42.0.0.json''']
               tokenizer.save_pretrained(_lowerCAmelCase      )
               _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
               self.assertEqual(len(_lowerCAmelCase      )							,  len(_lowerCAmelCase      )      )
               _lowerCAmelCase			      =	json.loads(new_tokenizer._tokenizer.to_str()      )
               self.assertNotIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )





   def 						__lowerCAmelCase				(						self      ):
         # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
         _lowerCAmelCase			      =	'''hf-internal-testing/test-two-tokenizers'''

         # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
         _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
         self.assertEqual(len(_lowerCAmelCase      )							,  28_997      )
         _lowerCAmelCase			      =	json.loads(tokenizer._tokenizer.to_str()      )
         self.assertIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )

         # Testing an older version by monkey-patching the version in the module it's used.
         import transformers as old_transformers

         _lowerCAmelCase			      =	'''3.0.0'''
         _lowerCAmelCase			      =	old_transformers.models.auto.AutoTokenizer.from_pretrained(_lowerCAmelCase      )
         self.assertEqual(len(_lowerCAmelCase      )							,  28_996      )
         _lowerCAmelCase			      =	json.loads(old_tokenizer._tokenizer.to_str()      )
         self.assertNotIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )






@require_tokenizers
class 		UpperCAmelCase    (    unittest.TestCase					):





   def 						__lowerCAmelCase				(						self      ):
         # See https://github.com/huggingface/transformers/pull/12550
         # and https://github.com/huggingface/tokenizers/issues/537
         _lowerCAmelCase			      =	PreTrainedTokenizerFast.from_pretrained('''robot-test/dummy-tokenizer-wordlevel'''      )
         _lowerCAmelCase			      =	'''The Matrix is a 1999 science fiction action film.'''

         with concurrent.futures.ThreadPoolExecutor() as executor:
               _lowerCAmelCase			      =	[executor.submit(self.fetch							,  _lowerCAmelCase							,  _lowerCAmelCase      ) for i in range(10      )]
               _lowerCAmelCase			      =	[future.result() for future in futures]
               self.assertEqual(_lowerCAmelCase							,  [[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10      )]      )





   def 						__lowerCAmelCase				(						self							,  _lowerCAmelCase							,  _lowerCAmelCase      ):
         return tokenizer.encode(_lowerCAmelCase							,  truncation='''longest_first'''							,  padding='''longest'''      )