
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
						from test_module.custom_tokenization_fast import CustomTokenizerFast





class   UpperCamelCase_      (      unittest.TestCase		):







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->int:
										# A mock response for an HTTP head request to emulate server down
										lowercase         =      mock.Mock()
										lowercase         =      500
										lowercase         =      {}
										lowercase         =      HTTPError
										lowercase         =      {}

										# Download this model to make sure it's in the cache.
										lowercase         =      BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"     )

										# Under the mock environment we get a 500 error when trying to reach the tokenizer.
										with mock.patch("requests.Session.request"		,    return_value=lowerCAmelCase__     ) as mock_head:
														lowercase         =      BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"     )
														# This check we did call the fake head request
														mock_head.assert_called()





						@require_tokenizers
						def        SCREAMING_SNAKE_CASE(			self							:Dict     )  ->str:
										# A mock response for an HTTP head request to emulate server down
										lowercase         =      mock.Mock()
										lowercase         =      500
										lowercase         =      {}
										lowercase         =      HTTPError
										lowercase         =      {}

										# Download this model to make sure it's in the cache.
										lowercase         =      GPTaTokenizerFast.from_pretrained("gpt2"     )

										# Under the mock environment we get a 500 error when trying to reach the tokenizer.
										with mock.patch("requests.Session.request"		,    return_value=lowerCAmelCase__     ) as mock_head:
														lowercase         =      GPTaTokenizerFast.from_pretrained("gpt2"     )
														# This check we did call the fake head request
														mock_head.assert_called()





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Optional[int]:
										# This test is for deprecated behavior and can be removed in v5
										try:
														lowercase         =      tempfile.mktemp()
														with open(lowerCAmelCase__		,    "wb"     ) as f:
																		http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"		,    lowerCAmelCase__     )

														lowercase         =      AlbertTokenizer.from_pretrained(lowerCAmelCase__     )
										finally:
														os.remove(lowerCAmelCase__     )

										# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
										# the current folder and have the right name.
										if os.path.isfile("tokenizer.json"     ):
														# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
														return
										try:
														with open("tokenizer.json"		,    "wb"     ) as f:
																		http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json"		,    lowerCAmelCase__     )
														lowercase         =      AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2"     )
														# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
														self.assertEqual(tokenizer.vocab_size		,    1000     )
														# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

										finally:
														os.remove("tokenizer.json"     )





						def        SCREAMING_SNAKE_CASE(			self							:str     )  ->Optional[Any]:
										# This test is for deprecated behavior and can be removed in v5
										lowercase         =      AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"     )





@is_staging_test
class   UpperCamelCase_      (      unittest.TestCase		):







						'''simple docstring'''



						UpperCamelCase      :  Optional[Any]				   =					['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']





						@classmethod
						def        SCREAMING_SNAKE_CASE(			cls							:Union[str, Any]     )  ->List[Any]:
										lowercase         =      TOKEN
										HfFolder.save_token(lowerCAmelCase__     )





						@classmethod
						def        SCREAMING_SNAKE_CASE(			cls							:Dict     )  ->int:
										try:
														delete_repo(token=cls._token		,    repo_id="test-tokenizer"     )
										except HTTPError:
														pass

										try:
														delete_repo(token=cls._token		,    repo_id="valid_org/test-tokenizer-org"     )
										except HTTPError:
														pass

										try:
														delete_repo(token=cls._token		,    repo_id="test-dynamic-tokenizer"     )
										except HTTPError:
														pass





						def        SCREAMING_SNAKE_CASE(			self							:Any     )  ->List[Any]:
										with tempfile.TemporaryDirectory() as tmp_dir:
														lowercase         =      os.path.join(lowerCAmelCase__		,    "vocab.txt"     )
														with open(lowerCAmelCase__		,    "w"		,    encoding="utf-8"     ) as vocab_writer:
																		vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]     )     )
														lowercase         =      BertTokenizer(lowerCAmelCase__     )

										tokenizer.push_to_hub("test-tokenizer"		,    use_auth_token=self._token     )
										lowercase         =      BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer'''     )
										self.assertDictEqual(new_tokenizer.vocab		,    tokenizer.vocab     )

										# Reset repo
										delete_repo(token=self._token		,    repo_id="test-tokenizer"     )

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
														tokenizer.save_pretrained(lowerCAmelCase__		,    repo_id="test-tokenizer"		,    push_to_hub=lowerCAmelCase__		,    use_auth_token=self._token     )

										lowercase         =      BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer'''     )
										self.assertDictEqual(new_tokenizer.vocab		,    tokenizer.vocab     )





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->Optional[Any]:
										with tempfile.TemporaryDirectory() as tmp_dir:
														lowercase         =      os.path.join(lowerCAmelCase__		,    "vocab.txt"     )
														with open(lowerCAmelCase__		,    "w"		,    encoding="utf-8"     ) as vocab_writer:
																		vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]     )     )
														lowercase         =      BertTokenizer(lowerCAmelCase__     )

										tokenizer.push_to_hub("valid_org/test-tokenizer-org"		,    use_auth_token=self._token     )
										lowercase         =      BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"     )
										self.assertDictEqual(new_tokenizer.vocab		,    tokenizer.vocab     )

										# Reset repo
										delete_repo(token=self._token		,    repo_id="valid_org/test-tokenizer-org"     )

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
														tokenizer.save_pretrained(
														    lowerCAmelCase__		,    repo_id="valid_org/test-tokenizer-org"		,    push_to_hub=lowerCAmelCase__		,    use_auth_token=self._token     )

										lowercase         =      BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"     )
										self.assertDictEqual(new_tokenizer.vocab		,    tokenizer.vocab     )





						@require_tokenizers
						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Any:
										CustomTokenizer.register_for_auto_class()
										with tempfile.TemporaryDirectory() as tmp_dir:
														lowercase         =      os.path.join(lowerCAmelCase__		,    "vocab.txt"     )
														with open(lowerCAmelCase__		,    "w"		,    encoding="utf-8"     ) as vocab_writer:
																		vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]     )     )
														lowercase         =      CustomTokenizer(lowerCAmelCase__     )

										# No fast custom tokenizer
										tokenizer.push_to_hub("test-dynamic-tokenizer"		,    use_auth_token=self._token     )

										lowercase         =      AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer'''		,    trust_remote_code=lowerCAmelCase__     )
										# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
										self.assertEqual(tokenizer.__class__.__name__		,    "CustomTokenizer"     )

										# Fast and slow custom tokenizer
										CustomTokenizerFast.register_for_auto_class()
										with tempfile.TemporaryDirectory() as tmp_dir:
														lowercase         =      os.path.join(lowerCAmelCase__		,    "vocab.txt"     )
														with open(lowerCAmelCase__		,    "w"		,    encoding="utf-8"     ) as vocab_writer:
																		vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]     )     )

														lowercase         =      BertTokenizerFast.from_pretrained(lowerCAmelCase__     )
														bert_tokenizer.save_pretrained(lowerCAmelCase__     )
														lowercase         =      CustomTokenizerFast.from_pretrained(lowerCAmelCase__     )

										tokenizer.push_to_hub("test-dynamic-tokenizer"		,    use_auth_token=self._token     )

										lowercase         =      AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer'''		,    trust_remote_code=lowerCAmelCase__     )
										# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
										self.assertEqual(tokenizer.__class__.__name__		,    "CustomTokenizerFast"     )
										lowercase         =      AutoTokenizer.from_pretrained(
										    F'''{USER}/test-dynamic-tokenizer'''		,    use_fast=lowerCAmelCase__		,    trust_remote_code=lowerCAmelCase__     )
										# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
										self.assertEqual(tokenizer.__class__.__name__		,    "CustomTokenizer"     )





class   UpperCamelCase_      (      unittest.TestCase		):







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->Dict:
										lowercase         =      Trie()
										trie.add("Hello 友達"     )
										self.assertEqual(trie.data		,    {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}     )
										trie.add("Hello"     )
										trie.data
										self.assertEqual(trie.data		,    {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}     )





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->List[Any]:
										lowercase         =      Trie()
										self.assertEqual(trie.split("[CLS] This is a extra_id_100"     )		,    ["[CLS] This is a extra_id_100"]     )
										trie.add("[CLS]"     )
										trie.add("extra_id_1"     )
										trie.add("extra_id_100"     )
										self.assertEqual(trie.split("[CLS] This is a extra_id_100"     )		,    ["[CLS]", " This is a ", "extra_id_100"]     )





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->Optional[Any]:
										lowercase         =      Trie()
										trie.add("A"     )
										self.assertEqual(trie.split("ABC"     )		,    ["A", "BC"]     )
										self.assertEqual(trie.split("BCA"     )		,    ["BC", "A"]     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]     )  ->List[Any]:
										lowercase         =      Trie()
										trie.add("TOKEN]"     )
										trie.add("[SPECIAL_TOKEN]"     )
										self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"     )		,    ["This is something ", "[SPECIAL_TOKEN]"]     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Dict:
										lowercase         =      Trie()
										trie.add("A"     )
										trie.add("P"     )
										trie.add("[SPECIAL_TOKEN]"     )
										self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"     )		,    ["This is something ", "[SPECIAL_TOKEN]"]     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]     )  ->Union[str, Any]:
										lowercase         =      Trie()
										trie.add("AB"     )
										trie.add("B"     )
										trie.add("C"     )
										self.assertEqual(trie.split("ABC"     )		,    ["AB", "C"]     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->int:
										lowercase         =      Trie()
										trie.add("ABC"     )
										trie.add("B"     )
										trie.add("CD"     )
										self.assertEqual(trie.split("ABCD"     )		,    ["ABC", "D"]     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Union[str, Any]:
										# Even if the offsets are wrong, we necessarily output correct string
										# parts.
										lowercase         =      Trie()
										lowercase         =      trie.cut_text("ABC"		,    [0, 0, 2, 1, 2, 3]     )
										self.assertEqual(lowerCAmelCase__		,    ["AB", "C"]     )


import inspect
import unittest

from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
						from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import MobileNetVaImageProcessor





class   UpperCamelCase_      (      __a		):







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->Optional[int]:
										lowercase         =      self.config_class(**self.inputs_dict     )
										self.parent.assertTrue(hasattr(lowerCAmelCase__		,    "tf_padding"     )     )
										self.parent.assertTrue(hasattr(lowerCAmelCase__		,    "depth_multiplier"     )     )





class   UpperCamelCase_      :







						'''simple docstring'''



						def __init__(			self							:Dict		,    lowerCAmelCase__							:Any		,    lowerCAmelCase__							:Union[str, Any]=13		,    lowerCAmelCase__							:Tuple=3		,    lowerCAmelCase__							:Optional[int]=32		,    lowerCAmelCase__							:Any=0.25		,    lowerCAmelCase__							:Dict=8		,    lowerCAmelCase__							:Optional[int]=8		,    lowerCAmelCase__							:List[str]=6		,    lowerCAmelCase__							:List[Any]=32		,    lowerCAmelCase__							:Optional[Any]=True		,    lowerCAmelCase__							:str=True		,    lowerCAmelCase__							:Optional[int]=True		,    lowerCAmelCase__							:Dict="relu6"		,    lowerCAmelCase__							:Tuple=1280		,    lowerCAmelCase__							:Dict=0.1		,    lowerCAmelCase__							:List[str]=0.02		,    lowerCAmelCase__							:Dict=True		,    lowerCAmelCase__							:List[Any]=True		,    lowerCAmelCase__							:Tuple=10		,    lowerCAmelCase__							:int=None		,    )  ->List[str]:
										lowercase         =      parent
										lowercase         =      batch_size
										lowercase         =      num_channels
										lowercase         =      image_size
										lowercase         =      depth_multiplier
										lowercase         =      depth_divisible_by
										lowercase         =      min_depth
										lowercase         =      expand_ratio
										lowercase         =      tf_padding
										lowercase         =      output_stride
										lowercase         =      first_layer_is_expansion
										lowercase         =      finegrained_output
										lowercase         =      hidden_act
										lowercase         =      last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier     )
										lowercase         =      classifier_dropout_prob
										lowercase         =      use_labels
										lowercase         =      is_training
										lowercase         =      num_labels
										lowercase         =      initializer_range
										lowercase         =      scope





						def        SCREAMING_SNAKE_CASE(			self							:str     )  ->Dict:
										lowercase         =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

										lowercase         =      None
										lowercase         =      None
										if self.use_labels:
														lowercase         =      ids_tensor([self.batch_size]		,    self.num_labels     )
														lowercase         =      ids_tensor([self.batch_size, self.image_size, self.image_size]		,    self.num_labels     )

										lowercase         =      self.get_config()

										return config, pixel_values, labels, pixel_labels





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->List[Any]:
										return MobileNetVaConfig(
										    num_channels=self.num_channels		,    image_size=self.image_size		,    depth_multiplier=self.depth_multiplier		,    depth_divisible_by=self.depth_divisible_by		,    min_depth=self.min_depth		,    expand_ratio=self.expand_ratio		,    output_stride=self.output_stride		,    first_layer_is_expansion=self.first_layer_is_expansion		,    finegrained_output=self.finegrained_output		,    hidden_act=self.hidden_act		,    tf_padding=self.tf_padding		,    classifier_dropout_prob=self.classifier_dropout_prob		,    initializer_range=self.initializer_range		,    )





						def        SCREAMING_SNAKE_CASE(			self							:Dict		,    lowerCAmelCase__							:Dict		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Tuple     )  ->Any:
										lowercase         =      MobileNetVaModel(config=lowerCAmelCase__     )
										model.to(lowerCAmelCase__     )
										model.eval()
										lowercase         =      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,
										    )		,    )
										self.parent.assertEqual(
										    result.pooler_output.shape		,    (self.batch_size, self.last_hidden_size)		,    )





						def        SCREAMING_SNAKE_CASE(			self							:Tuple		,    lowerCAmelCase__							:int		,    lowerCAmelCase__							:List[str]		,    lowerCAmelCase__							:str		,    lowerCAmelCase__							:Optional[Any]     )  ->Union[str, Any]:
										lowercase         =      self.num_labels
										lowercase         =      MobileNetVaForImageClassification(lowerCAmelCase__     )
										model.to(lowerCAmelCase__     )
										model.eval()
										lowercase         =      model(lowerCAmelCase__		,    labels=lowerCAmelCase__     )
										self.parent.assertEqual(result.logits.shape		,    (self.batch_size, self.num_labels)     )





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





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







						'''simple docstring'''



						UpperCamelCase      :  Optional[int]				   =					(
						    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase      :  List[Any]				   =					(
						    {
						        '''feature-extraction''': MobileNetVaModel,
						        '''image-classification''': MobileNetVaForImageClassification,
						        '''image-segmentation''': MobileNetVaForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase      :  Union[str, Any]				   =					False
						UpperCamelCase      :  int				   =					False
						UpperCamelCase      :  str				   =					False
						UpperCamelCase      :  Dict				   =					False





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Dict:
										lowercase         =      MobileNetVaModelTester(self     )
										lowercase         =      MobileNetVaConfigTester(self		,    config_class=lowerCAmelCase__		,    has_text_modality=lowerCAmelCase__     )





						def        SCREAMING_SNAKE_CASE(			self							:Dict     )  ->Any:
										self.config_tester.run_common_tests()





						@unittest.skip(reason="MobileNetV2 does not use inputs_embeds"     )
						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->Optional[int]:
										pass





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





						@unittest.skip(reason="MobileNetV2 does not output attentions"     )
						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->str:
										pass





						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->Dict:
										lowercase     ,	lowercase         =      self.model_tester.prepare_config_and_inputs_for_common()

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

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





						def        SCREAMING_SNAKE_CASE(			self							:int     )  ->List[str]:
										lowercase         =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__     )





						def        SCREAMING_SNAKE_CASE(			self							:int     )  ->Optional[int]:
										def check_hidden_states_output(lowerCAmelCase__							:str		,    lowerCAmelCase__							:Union[str, Any]		,    lowerCAmelCase__							:int     ):
														lowercase         =      model_class(lowerCAmelCase__     )
														model.to(lowerCAmelCase__     )
														model.eval()

														with torch.no_grad():
																		lowercase         =      model(**self._prepare_for_class(lowerCAmelCase__		,    lowerCAmelCase__     )     )

														lowercase         =      outputs.hidden_states

														lowercase         =      16
														self.assertEqual(len(lowerCAmelCase__     )		,    lowerCAmelCase__     )

										lowercase     ,	lowercase         =      self.model_tester.prepare_config_and_inputs_for_common()

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

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

														check_hidden_states_output(lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )





						def        SCREAMING_SNAKE_CASE(			self							:Any     )  ->Tuple:
										lowercase         =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__     )





						def        SCREAMING_SNAKE_CASE(			self							:int     )  ->str:
										lowercase         =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase__     )





						@slow
						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->str:
										for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowercase         =      MobileNetVaModel.from_pretrained(lowerCAmelCase__     )
														self.assertIsNotNone(lowerCAmelCase__     )




def  __snake_case							(	):







				'''simple docstring'''


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





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







						'''simple docstring'''



						@cached_property
						def        SCREAMING_SNAKE_CASE(			self							:str     )  ->Any:
										return (
										    MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"     ) if is_vision_available() else None
										)





						@slow
						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->Union[str, Any]:
										lowercase         =      MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"     ).to(lowerCAmelCase__     )

										lowercase         =      self.default_image_processor
										lowercase         =      prepare_img()
										lowercase         =      image_processor(images=lowerCAmelCase__		,    return_tensors="pt"     ).to(lowerCAmelCase__     )

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

										# verify the logits
										lowercase         =      torch.Size((1, 1001)     )
										self.assertEqual(outputs.logits.shape		,    lowerCAmelCase__     )

										lowercase         =      torch.tensor([0.24_45, -1.19_93, 0.19_05]     ).to(lowerCAmelCase__     )

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





						@slow
						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->List[Any]:
										lowercase         =      MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"     )
										lowercase         =      model.to(lowerCAmelCase__     )

										lowercase         =      MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"     )

										lowercase         =      prepare_img()
										lowercase         =      image_processor(images=lowerCAmelCase__		,    return_tensors="pt"     ).to(lowerCAmelCase__     )

										# forward pass
										with torch.no_grad():
														lowercase         =      model(**lowerCAmelCase__     )
										lowercase         =      outputs.logits

										# verify the logits
										lowercase         =      torch.Size((1, 21, 65, 65)     )
										self.assertEqual(logits.shape		,    lowerCAmelCase__     )

										lowercase         =      torch.tensor(
										    [
										        [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
										        [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
										        [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
										    ]		,    device=lowerCAmelCase__		,    )

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