






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       __lowercase      (	lowercase_  ):







     '''simple docstring'''




     def 		lowerCAmelCase_     (				self       :			Tuple				):


         """simple docstring"""



         __A         =	self.config_class(**self.inputs_dict				)
         self.parent.assertTrue(hasattr(UpperCamelCase_ ,	"""tf_padding"""				)				)
         self.parent.assertTrue(hasattr(UpperCamelCase_ ,	"""depth_multiplier"""				)				)


class       __lowercase      :







     '''simple docstring'''




     def __init__(				self       :			List[Any] ,	UpperCamelCase_       :			Dict ,	UpperCamelCase_       :			Optional[int]=13 ,	UpperCamelCase_       :			str=3 ,	UpperCamelCase_       :			Union[str, Any]=32 ,	UpperCamelCase_       :			Dict=0.25 ,	UpperCamelCase_       :			Optional[int]=8 ,	UpperCamelCase_       :			Dict=8 ,	UpperCamelCase_       :			List[str]=6 ,	UpperCamelCase_       :			Any=32 ,	UpperCamelCase_       :			Optional[Any]=True ,	UpperCamelCase_       :			List[Any]=True ,	UpperCamelCase_       :			Dict=True ,	UpperCamelCase_       :			Union[str, Any]="relu6" ,	UpperCamelCase_       :			int=1_280 ,	UpperCamelCase_       :			str=0.1 ,	UpperCamelCase_       :			List[Any]=0.02 ,	UpperCamelCase_       :			int=True ,	UpperCamelCase_       :			Optional[Any]=True ,	UpperCamelCase_       :			Optional[Any]=10 ,	UpperCamelCase_       :			Any=None ,	):


         """simple docstring"""



         __A         =	parent
         __A         =	batch_size
         __A         =	num_channels
         __A         =	image_size
         __A         =	depth_multiplier
         __A         =	depth_divisible_by
         __A         =	min_depth
         __A         =	expand_ratio
         __A         =	tf_padding
         __A         =	output_stride
         __A         =	first_layer_is_expansion
         __A         =	finegrained_output
         __A         =	hidden_act
         __A         =	last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier				)
         __A         =	classifier_dropout_prob
         __A         =	use_labels
         __A         =	is_training
         __A         =	num_labels
         __A         =	initializer_range
         __A         =	scope




     def 		lowerCAmelCase_     (				self       :			Any				):


         """simple docstring"""



         __A         =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

         __A         =	self.get_config()

         return config, pixel_values, labels, pixel_labels




     def 		lowerCAmelCase_     (				self       :			Optional[int]				):


         """simple docstring"""



         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 		lowerCAmelCase_     (				self       :			Union[str, Any] ,	UpperCamelCase_       :			Optional[Any] ,	UpperCamelCase_       :			Any ,	UpperCamelCase_       :			str ,	UpperCamelCase_       :			Optional[int]				):


         """simple docstring"""



         __A         =	MobileNetVaModel(config=UpperCamelCase_				)
         model.to(UpperCamelCase_				)
         model.eval()
         __A         =	model(UpperCamelCase_				)
         self.parent.assertEqual(
             result.last_hidden_state.shape ,	(
                 self.batch_size,
                 self.last_hidden_size,
                 self.image_size // self.output_stride,
                 self.image_size // self.output_stride,
             ) ,	)
         self.parent.assertEqual(
             result.pooler_output.shape ,	(self.batch_size, self.last_hidden_size) ,	)




     def 		lowerCAmelCase_     (				self       :			Any ,	UpperCamelCase_       :			List[str] ,	UpperCamelCase_       :			List[str] ,	UpperCamelCase_       :			int ,	UpperCamelCase_       :			List[str]				):


         """simple docstring"""



         __A         =	self.num_labels
         __A         =	MobileNetVaForImageClassification(UpperCamelCase_				)
         model.to(UpperCamelCase_				)
         model.eval()
         __A         =	model(UpperCamelCase_ ,	labels=UpperCamelCase_				)
         self.parent.assertEqual(result.logits.shape ,	(self.batch_size, self.num_labels)				)




     def 		lowerCAmelCase_     (				self       :			List[Any] ,	UpperCamelCase_       :			str ,	UpperCamelCase_       :			Optional[int] ,	UpperCamelCase_       :			List[Any] ,	UpperCamelCase_       :			int				):


         """simple docstring"""



         __A         =	self.num_labels
         __A         =	MobileNetVaForSemanticSegmentation(UpperCamelCase_				)
         model.to(UpperCamelCase_				)
         model.eval()
         __A         =	model(UpperCamelCase_				)
         self.parent.assertEqual(
             result.logits.shape ,	(
                 self.batch_size,
                 self.num_labels,
                 self.image_size // self.output_stride,
                 self.image_size // self.output_stride,
             ) ,	)
         __A         =	model(UpperCamelCase_ ,	labels=UpperCamelCase_				)
         self.parent.assertEqual(
             result.logits.shape ,	(
                 self.batch_size,
                 self.num_labels,
                 self.image_size // self.output_stride,
                 self.image_size // self.output_stride,
             ) ,	)





     def 		lowerCAmelCase_     (				self       :			Union[str, Any]				):


         """simple docstring"""



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


@require_torch
class       __lowercase      (	lowercase_			,      lowercase_			,      unittest.TestCase  ):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE   						=				(
         (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE   						=				(
         {
             "feature-extraction": MobileNetVaModel,
             "image-classification": MobileNetVaForImageClassification,
             "image-segmentation": MobileNetVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE   						=				False
     SCREAMING_SNAKE_CASE   						=				False
     SCREAMING_SNAKE_CASE   						=				False
     SCREAMING_SNAKE_CASE   						=				False




     def 		lowerCAmelCase_     (				self       :			List[str]				):


         """simple docstring"""



         __A         =	MobileNetVaModelTester(self				)
         __A         =	MobileNetVaConfigTester(self ,	config_class=UpperCamelCase_ ,	has_text_modality=UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			int				):


         """simple docstring"""



         self.config_tester.run_common_tests()




     @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds"""				)
     def 		lowerCAmelCase_     (				self       :			Any				):


         """simple docstring"""



         pass




     @unittest.skip(reason="""MobileNetV2 does not support input and output embeddings"""				)
     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         pass




     @unittest.skip(reason="""MobileNetV2 does not output attentions"""				)
     def 		lowerCAmelCase_     (				self       :			Optional[Any]				):


         """simple docstring"""



         pass




     def 		lowerCAmelCase_     (				self       :			List[str]				):


         """simple docstring"""



         __A    ,	__A         =	self.model_tester.prepare_config_and_inputs_for_common()

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

             __A         =	["""pixel_values"""]
             self.assertListEqual(arg_names[:1] ,	UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         __A         =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			List[str]				):


         """simple docstring"""



         def check_hidden_states_output(UpperCamelCase_       :			List[str] ,	UpperCamelCase_       :			Optional[int] ,	UpperCamelCase_       :			Dict				):
             __A         =	model_class(UpperCamelCase_				)
             model.to(UpperCamelCase_				)
             model.eval()

             with torch.no_grad():
                 __A         =	model(**self._prepare_for_class(UpperCamelCase_ ,	UpperCamelCase_				)				)

             __A         =	outputs.hidden_states

             __A         =	16
             self.assertEqual(len(UpperCamelCase_				) ,	UpperCamelCase_				)

         __A    ,	__A         =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             __A         =	True
             check_hidden_states_output(UpperCamelCase_ ,	UpperCamelCase_ ,	UpperCamelCase_				)

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

             check_hidden_states_output(UpperCamelCase_ ,	UpperCamelCase_ ,	UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			Any				):


         """simple docstring"""



         __A         =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         __A         =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase_				)





     @slow
     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __A         =	MobileNetVaModel.from_pretrained(UpperCamelCase_				)
             self.assertIsNotNone(UpperCamelCase_				)



def 			_SCREAMING_SNAKE_CASE						( )						->      Dict:





    """simple docstring"""

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






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







     '''simple docstring'''




     @cached_property
     def 		lowerCAmelCase_     (				self       :			List[str]				):


         """simple docstring"""



         return (
             MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v2_1.0_224"""				) if is_vision_available() else None
         )




     @slow
     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         __A         =	MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224"""				).to(UpperCamelCase_				)

         __A         =	self.default_image_processor
         __A         =	prepare_img()
         __A         =	image_processor(images=UpperCamelCase_ ,	return_tensors="""pt"""				).to(UpperCamelCase_				)

         # forward pass
         with torch.no_grad():
             __A         =	model(**UpperCamelCase_				)

         # verify the logits
         __A         =	torch.Size((1, 1_001)				)
         self.assertEqual(outputs.logits.shape ,	UpperCamelCase_				)

         __A         =	torch.tensor([0.2445, -1.1993, 0.1905]				).to(UpperCamelCase_				)

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





     @slow
     def 		lowerCAmelCase_     (				self       :			List[Any]				):


         """simple docstring"""



         __A         =	MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""				)
         __A         =	model.to(UpperCamelCase_				)

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

         __A         =	prepare_img()
         __A         =	image_processor(images=UpperCamelCase_ ,	return_tensors="""pt"""				).to(UpperCamelCase_				)

         # forward pass
         with torch.no_grad():
             __A         =	model(**UpperCamelCase_				)
         __A         =	outputs.logits

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

         __A         =	torch.tensor(
             [
                 [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
                 [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
                 [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
             ] ,	device=UpperCamelCase_ ,	)

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












from typing import TYPE_CHECKING

from ...utils import _LazyModule


__a      :       Optional[int]				  =   {"tokenization_bertweet": ["BertweetTokenizer"]}


if TYPE_CHECKING:
  from .tokenization_bertweet import BertweetTokenizer

else:
  import sys

  __a      :       int				  =   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




