



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, MobileNetVaModel
   from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import MobileNetVaImageProcessor


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		self.config_class(**self.inputs_dict)
             self.parent.assertTrue(hasattr(_UpperCAmelCase     ,"tf_padding"))
             self.parent.assertTrue(hasattr(_UpperCAmelCase     ,"depth_multiplier"))


class   snake_case_ :




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase=13     ,lowercase=3     ,lowercase=32     ,lowercase=0.25     ,lowercase=8     ,lowercase=True     ,lowercase=1024     ,lowercase=32     ,lowercase="relu6"     ,lowercase=0.1     ,lowercase=0.02     ,lowercase=True     ,lowercase=True     ,lowercase=10     ,lowercase=None     ,):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		parent
             UpperCAmelCase_  :	Optional[Any]				      =		batch_size
             UpperCAmelCase_  :	Union[str, Any]				      =		num_channels
             UpperCAmelCase_  :	Optional[int]				      =		image_size
             UpperCAmelCase_  :	Optional[int]				      =		depth_multiplier
             UpperCAmelCase_  :	Any				      =		min_depth
             UpperCAmelCase_  :	List[str]				      =		tf_padding
             UpperCAmelCase_  :	int				      =		int(last_hidden_size * depth_multiplier)
             UpperCAmelCase_  :	Tuple				      =		output_stride
             UpperCAmelCase_  :	int				      =		hidden_act
             UpperCAmelCase_  :	Optional[int]				      =		classifier_dropout_prob
             UpperCAmelCase_  :	Optional[Any]				      =		use_labels
             UpperCAmelCase_  :	str				      =		is_training
             UpperCAmelCase_  :	Union[str, Any]				      =		num_labels
             UpperCAmelCase_  :	Tuple				      =		initializer_range
             UpperCAmelCase_  :	Any				      =		scope



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

             UpperCAmelCase_  :	str				      =		None
             UpperCAmelCase_  :	Tuple				      =		None
             if self.use_labels:
                   UpperCAmelCase_  :	Optional[Any]				      =		ids_tensor([self.batch_size]     ,self.num_labels)
                   UpperCAmelCase_  :	Optional[int]				      =		ids_tensor([self.batch_size, self.image_size, self.image_size]     ,self.num_labels)

             UpperCAmelCase_  :	Union[str, Any]				      =		self.get_config()

             return config, pixel_values, labels, pixel_labels



       def  A_   (     self):

             """simple docstring"""





             return MobileNetVaConfig(
                 num_channels=self.num_channels     ,image_size=self.image_size     ,depth_multiplier=self.depth_multiplier     ,min_depth=self.min_depth     ,tf_padding=self.tf_padding     ,hidden_act=self.hidden_act     ,classifier_dropout_prob=self.classifier_dropout_prob     ,initializer_range=self.initializer_range     ,)



       def  A_   (     self     ,lowercase     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[int]				      =		MobileNetVaModel(config=_UpperCAmelCase)
             model.to(_UpperCAmelCase)
             model.eval()
             UpperCAmelCase_  :	Tuple				      =		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,
                 )     ,)



       def  A_   (     self     ,lowercase     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[int]				      =		self.num_labels
             UpperCAmelCase_  :	int				      =		MobileNetVaForImageClassification(_UpperCAmelCase)
             model.to(_UpperCAmelCase)
             model.eval()
             UpperCAmelCase_  :	Optional[Any]				      =		model(_UpperCAmelCase     ,labels=_UpperCAmelCase)
             self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.num_labels))



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		self.prepare_config_and_inputs()
             UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_  :	Optional[Any]				      =		config_and_inputs
             UpperCAmelCase_  :	Dict				      =		{"pixel_values": pixel_values}
             return config, inputs_dict


@require_torch
class   snake_case_ (lowercase__ , lowercase__ , unittest.TestCase  ):




       """simple docstring"""






       _lowerCamelCase			    =				(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
       _lowerCamelCase			    =				(
           {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
           if is_torch_available()
           else {}
       )

       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		MobileNetVaModelTester(self)
             UpperCAmelCase_  :	Union[str, Any]				      =		MobileNetVaConfigTester(self     ,config_class=_UpperCAmelCase     ,has_text_modality=_UpperCAmelCase)



       def  A_   (     self):

             """simple docstring"""





             self.config_tester.run_common_tests()



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

             """simple docstring"""





             pass



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

             """simple docstring"""





             pass



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

             """simple docstring"""





             pass



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_      ,      UpperCAmelCase_  :	Optional[int]				      =		self.model_tester.prepare_config_and_inputs_for_common()

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

                   UpperCAmelCase_  :	List[Any]				      =		["pixel_values"]
                   self.assertListEqual(arg_names[:1]     ,_UpperCAmelCase)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[Any]				      =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase)



       def  A_   (     self):

             """simple docstring"""





             def check_hidden_states_output(lowercase     ,lowercase     ,lowercase):
                   UpperCAmelCase_  :	Optional[int]				      =		model_class(_UpperCAmelCase)
                   model.to(_UpperCAmelCase)
                   model.eval()

                   with torch.no_grad():
                         UpperCAmelCase_  :	Any				      =		model(**self._prepare_for_class(_UpperCAmelCase     ,_UpperCAmelCase))

                   UpperCAmelCase_  :	List[Any]				      =		outputs.hidden_states

                   UpperCAmelCase_  :	Tuple				      =		26
                   self.assertEqual(len(_UpperCAmelCase)     ,_UpperCAmelCase)

             UpperCAmelCase_      ,      UpperCAmelCase_  :	List[str]				      =		self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_  :	int				      =		True
                   check_hidden_states_output(_UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase)

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

                   check_hidden_states_output(_UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	str				      =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase)



       @slow
       def  A_   (     self):

             """simple docstring"""





             for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_  :	Union[str, Any]				      =		MobileNetVaModel.from_pretrained(_UpperCAmelCase)
                   self.assertIsNotNone(_UpperCAmelCase)







def    _snake_case (       )     ->     str:






      '''simple docstring'''







      UpperCAmelCase_  :	List[Any]				      =		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
      return image





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




       """simple docstring"""






       @cached_property
       def  A_   (     self):

             """simple docstring"""





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



       @slow
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224").to(_UpperCAmelCase)

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

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

             # verify the logits
             UpperCAmelCase_  :	Optional[int]				      =		torch.Size((1, 1001))
             self.assertEqual(outputs.logits.shape     ,_UpperCAmelCase)

             UpperCAmelCase_  :	int				      =		torch.tensor([-4.1739, -1.1233, 3.1205]).to(_UpperCAmelCase)

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





from typing import Mapping

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


__lowerCamelCase         =			logging.get_logger(__name__)

__lowerCamelCase         =			{
    '''google/umt5-small''': '''https://huggingface.co/google/umt5-small/resolve/main/config.json''',
    # See all umt5 models at https://huggingface.co/models?filter=umt5
}


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       _lowerCamelCase			    =				"""umt5"""
       _lowerCamelCase			    =				["""past_key_values"""]



       def __init__(     self     ,lowercase=250112     ,lowercase=512     ,lowercase=64     ,lowercase=1024     ,lowercase=8     ,lowercase=None     ,lowercase=6     ,lowercase=32     ,lowercase=128     ,lowercase=0.1     ,lowercase=1E-6     ,lowercase=1.0     ,lowercase="gated-gelu"     ,lowercase=True     ,lowercase=True     ,lowercase="T5Tokenizer"     ,lowercase=True     ,lowercase=0     ,lowercase=1     ,lowercase=0     ,**lowercase     ,):

             """simple docstring"""





             super().__init__(
                 is_encoder_decoder=lowercase     ,tokenizer_class=lowercase     ,tie_word_embeddings=lowercase     ,pad_token_id=lowercase     ,eos_token_id=lowercase     ,decoder_start_token_id=lowercase     ,**lowercase     ,)
             UpperCAmelCase_  :	Optional[int]				      =		vocab_size
             UpperCAmelCase_  :	Any				      =		d_model
             UpperCAmelCase_  :	Any				      =		d_kv
             UpperCAmelCase_  :	int				      =		d_ff
             UpperCAmelCase_  :	Tuple				      =		num_layers
             UpperCAmelCase_  :	int				      =		(
                 num_decoder_layers if num_decoder_layers is not None else self.num_layers
             )  # default = symmetry
             UpperCAmelCase_  :	Optional[int]				      =		num_heads
             UpperCAmelCase_  :	str				      =		relative_attention_num_buckets
             UpperCAmelCase_  :	Any				      =		relative_attention_max_distance
             UpperCAmelCase_  :	Optional[Any]				      =		dropout_rate
             UpperCAmelCase_  :	Union[str, Any]				      =		layer_norm_epsilon
             UpperCAmelCase_  :	Optional[Any]				      =		initializer_factor
             UpperCAmelCase_  :	int				      =		feed_forward_proj
             UpperCAmelCase_  :	str				      =		use_cache

             UpperCAmelCase_  :	List[str]				      =		self.feed_forward_proj.split("-")
             UpperCAmelCase_  :	Any				      =		act_info[-1]
             UpperCAmelCase_  :	Optional[int]				      =		act_info[0] == "gated"

             if len(lowercase) > 1 and act_info[0] != "gated" or len(lowercase) > 2:
                   raise ValueError(
                       F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
                       "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
                       "'gated-gelu' or 'relu'")

             if feed_forward_proj == "gated-gelu":
                   UpperCAmelCase_  :	Tuple				      =		"gelu_new"



       @property
       def  A_   (     self):

             """simple docstring"""





             return self.d_model



       @property
       def  A_   (     self):

             """simple docstring"""





             return self.num_heads



       @property
       def  A_   (     self):

             """simple docstring"""





             return self.num_layers


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       @property
       # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		{
                 "input_ids": {0: "batch", 1: "encoder_sequence"},
                 "attention_mask": {0: "batch", 1: "encoder_sequence"},
             }
             if self.use_past:
                   UpperCAmelCase_  :	Union[str, Any]				      =		"past_encoder_sequence + sequence"
                   UpperCAmelCase_  :	Optional[int]				      =		{0: "batch"}
                   UpperCAmelCase_  :	Union[str, Any]				      =		{0: "batch", 1: "past_decoder_sequence + sequence"}
             else:
                   UpperCAmelCase_  :	Optional[int]				      =		{0: "batch", 1: "decoder_sequence"}
                   UpperCAmelCase_  :	Dict				      =		{0: "batch", 1: "decoder_sequence"}

             if self.use_past:
                   self.fill_with_past_key_values_(lowercase     ,direction="inputs")

             return common_inputs



       @property
       # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
       def  A_   (     self):

             """simple docstring"""





             return 13



       @property
       def  A_   (     self):

             """simple docstring"""





             return 5E-4
