





"""simple docstring"""




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__		):






							def 					__a     (     self   )			->				Optional[int]:
								a   :	List[Any]			=       self.config_class(**self.inputs_dict   )
								self.parent.assertTrue(hasattr(lowerCAmelCase__   ,      "tf_padding"   )   )
								self.parent.assertTrue(hasattr(lowerCAmelCase__   ,      "depth_multiplier"   )   )


class  __UpperCamelCase       :






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






							def 					__a     (     self   )			->				str:
								a   :	Any			=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

								a   :	List[str]			=       self.get_config()

								return config, pixel_values, labels, pixel_labels






							def 					__a     (     self   )			->				List[str]:
								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 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				Optional[Any]:
								a   :	int			=       MobileNetVaModel(config=lowerCAmelCase__   )
								model.to(lowerCAmelCase__   )
								model.eval()
								a   :	Tuple			=       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 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				List[str]:
								a   :	Optional[int]			=       self.num_labels
								a   :	Tuple			=       MobileNetVaForImageClassification(lowerCAmelCase__   )
								model.to(lowerCAmelCase__   )
								model.eval()
								a   :	Dict			=       model(lowerCAmelCase__   ,      labels=lowerCAmelCase__   )
								self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_labels)   )






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


@require_torch
class  __UpperCamelCase       (		a__	, a__	, unittest.TestCase		):
							lowerCamelCase     :      Dict         =(
							    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							lowerCamelCase     :      Optional[int]         =(
							    {
							        """feature-extraction""": MobileNetVaModel,
							        """image-classification""": MobileNetVaForImageClassification,
							        """image-segmentation""": MobileNetVaForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							lowerCamelCase     :      Tuple         =False
							lowerCamelCase     :      Dict         =False
							lowerCamelCase     :      Optional[Any]         =False
							lowerCamelCase     :      Optional[int]         =False






							def 					__a     (     self   )			->				List[Any]:
								a   :	Union[str, Any]			=       MobileNetVaModelTester(self   )
								a   :	Any			=       MobileNetVaConfigTester(self   ,      config_class=lowerCAmelCase__   ,      has_text_modality=lowerCAmelCase__   )






							def 					__a     (     self   )			->				str:
								self.config_tester.run_common_tests()






							@unittest.skip(reason="MobileNetV2 does not use inputs_embeds"   )
							def 					__a     (     self   )			->				str:
								pass






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






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






							def 					__a     (     self   )			->				Optional[int]:
								a, a   :	List[Any]			=       self.model_tester.prepare_config_and_inputs_for_common()

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

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






							def 					__a     (     self   )			->				Optional[int]:
								a   :	Dict			=       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCAmelCase__   )






							def 					__a     (     self   )			->				Optional[int]:
								def check_hidden_states_output(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ):
									a   :	List[Any]			=       model_class(lowerCAmelCase__   )
									model.to(lowerCAmelCase__   )
									model.eval()

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

									a   :	Optional[int]			=       outputs.hidden_states

									a   :	int			=       16
									self.assertEqual(len(lowerCAmelCase__   )   ,      lowerCAmelCase__   )

								a, a   :	Dict			=       self.model_tester.prepare_config_and_inputs_for_common()

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

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									a   :	Union[str, Any]			=       True

									check_hidden_states_output(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )






							def 					__a     (     self   )			->				List[Any]:
								a   :	Union[str, Any]			=       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__   )






							def 					__a     (     self   )			->				Any:
								a   :	str			=       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase__   )






							@slow
							def 					__a     (     self   )			->				str:
								for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									a   :	Tuple			=       MobileNetVaModel.from_pretrained(lowerCAmelCase__   )
									self.assertIsNotNone(lowerCAmelCase__   )






def    _SCREAMING_SNAKE_CASE	(			)				->Tuple:






	'''simple docstring'''






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







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






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






							@slow
							def 					__a     (     self   )			->				List[str]:
								a   :	Optional[Any]			=       MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"   ).to(lowerCAmelCase__   )

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

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

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

								a   :	Tuple			=       torch.tensor([0.2_445, -1.1_993, 0.1_905]   ).to(lowerCAmelCase__   )

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






							@slow
							def 					__a     (     self   )			->				int:
								a   :	int			=       MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"   )
								a   :	Optional[Any]			=       model.to(lowerCAmelCase__   )

								a   :	List[Any]			=       MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"   )

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

								# forward pass
								with torch.no_grad():
									a   :	int			=       model(**lowerCAmelCase__   )
								a   :	Optional[int]			=       outputs.logits

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

								a   :	Optional[int]			=       torch.tensor(
								    [
								        [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
								        [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]],
								        [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]],
								    ]   ,      device=lowerCAmelCase__   ,      )

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









"""simple docstring"""




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


if is_sentencepiece_available():
		from ..ta.tokenization_ta import TaTokenizer
else:
		from ...utils.dummy_sentencepiece_objects import TaTokenizer

a		:				List[Any]  			=    TaTokenizer

if is_tokenizers_available():
		from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
		from ...utils.dummy_tokenizers_objects import TaTokenizerFast

a		:				Union[str, Any]  			=    TaTokenizerFast

a		:				Union[str, Any]  			=    {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a		:				str  			=    [
		    '''MT5EncoderModel''',
		    '''MT5ForConditionalGeneration''',
		    '''MT5ForQuestionAnswering''',
		    '''MT5Model''',
		    '''MT5PreTrainedModel''',
		    '''MT5Stack''',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a		:				List[str]  			=    ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model''']

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a		:				Optional[Any]  			=    ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model''']


if TYPE_CHECKING:
		from .configuration_mta import MTaConfig, MTaOnnxConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_mta import (
				    MTaEncoderModel,
				    MTaForConditionalGeneration,
				    MTaForQuestionAnswering,
				    MTaModel,
				    MTaPreTrainedModel,
				    MTaStack,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel

else:
		import sys

		a		:				List[Any]  			=    _LazyModule(
		    __name__,
		    globals()['''__file__'''],
		    _import_structure,
		    extra_objects={'''MT5Tokenizer''': MTaTokenizer, '''MT5TokenizerFast''': MTaTokenizerFast},
		    module_spec=__spec__,
		)


