


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







      '''simple docstring'''




      def 						lowercase_ (				self							)					->    str:
          lowerCAmelCase_ :      Union[str, Any]    				=				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=1_3   ,						__lowercase=3   ,						__lowercase=3_2   ,						__lowercase=0.25   ,						__lowercase=8   ,						__lowercase=True   ,						__lowercase=1_0_2_4   ,						__lowercase=3_2   ,						__lowercase="relu6"   ,						__lowercase=0.1   ,						__lowercase=0.02   ,						__lowercase=True   ,						__lowercase=True   ,						__lowercase=1_0   ,						__lowercase=None   ,						)					->    Any:
          lowerCAmelCase_ :      Any    				=				parent
          lowerCAmelCase_ :      Dict    				=				batch_size
          lowerCAmelCase_ :      Union[str, Any]    				=				num_channels
          lowerCAmelCase_ :      Any    				=				image_size
          lowerCAmelCase_ :      Optional[int]    				=				depth_multiplier
          lowerCAmelCase_ :      List[str]    				=				min_depth
          lowerCAmelCase_ :      Union[str, Any]    				=				tf_padding
          lowerCAmelCase_ :      Dict    				=				int(last_hidden_size * depth_multiplier							)
          lowerCAmelCase_ :      int    				=				output_stride
          lowerCAmelCase_ :      List[Any]    				=				hidden_act
          lowerCAmelCase_ :      Dict    				=				classifier_dropout_prob
          lowerCAmelCase_ :      List[Any]    				=				use_labels
          lowerCAmelCase_ :      int    				=				is_training
          lowerCAmelCase_ :      Tuple    				=				num_labels
          lowerCAmelCase_ :      Tuple    				=				initializer_range
          lowerCAmelCase_ :      int    				=				scope




      def 						lowercase_ (				self							)					->    int:
          lowerCAmelCase_ :      int    				=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

          lowerCAmelCase_ :      str    				=				self.get_config()

          return config, pixel_values, labels, pixel_labels




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




      def 						lowercase_ (				self							)					->    List[Any]:
          lowerCAmelCase_ :      List[str]    				=				self.prepare_config_and_inputs()
          lowerCAmelCase_ :      Any    				=				config_and_inputs
          lowerCAmelCase_ :      Tuple    				=				{'''pixel_values''': pixel_values}
          return config, inputs_dict







@require_torch
class 				snake_case__(							SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_,						unittest.TestCase							):







      '''simple docstring'''




      SCREAMING_SNAKE_CASE__      :  List[str]					=							(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
      SCREAMING_SNAKE_CASE__      :  List[str]					=							(
          {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
          if is_torch_available()
          else {}
      )

      SCREAMING_SNAKE_CASE__      :  str					=							False
      SCREAMING_SNAKE_CASE__      :  Dict					=							False
      SCREAMING_SNAKE_CASE__      :  Optional[Any]					=							False
      SCREAMING_SNAKE_CASE__      :  List[str]					=							False




      def 						lowercase_ (				self							)					->    Optional[int]:
          lowerCAmelCase_ :      List[Any]    				=				MobileNetVaModelTester(self							)
          lowerCAmelCase_ :      Dict    				=				MobileNetVaConfigTester(self   ,						config_class=UpperCamelCase__   ,						has_text_modality=UpperCamelCase__							)




      def 						lowercase_ (				self							)					->    Tuple:
          self.config_tester.run_common_tests()




      @unittest.skip(reason='''MobileNetV1 does not use inputs_embeds'''							)
      def 						lowercase_ (				self							)					->    Optional[int]:
          pass




      @unittest.skip(reason='''MobileNetV1 does not support input and output embeddings'''							)
      def 						lowercase_ (				self							)					->    Union[str, Any]:
          pass




      @unittest.skip(reason='''MobileNetV1 does not output attentions'''							)
      def 						lowercase_ (				self							)					->    Tuple:
          pass




      def 						lowercase_ (				self							)					->    Dict:
          lowerCAmelCase_ :      int    				=				self.model_tester.prepare_config_and_inputs_for_common()

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

              lowerCAmelCase_ :      Tuple    				=				['''pixel_values''']
              self.assertListEqual(arg_names[:1]   ,						UpperCamelCase__							)




      def 						lowercase_ (				self							)					->    List[str]:
          lowerCAmelCase_ :      Union[str, Any]    				=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*UpperCamelCase__							)




      def 						lowercase_ (				self							)					->    Any:
          def check_hidden_states_output(__lowercase   ,						__lowercase   ,						__lowercase							):
              lowerCAmelCase_ :      List[str]    				=				model_class(UpperCamelCase__							)
              model.to(UpperCamelCase__							)
              model.eval()

              with torch.no_grad():
                  lowerCAmelCase_ :      List[str]    				=				model(**self._prepare_for_class(UpperCamelCase__   ,						UpperCamelCase__							)							)

              lowerCAmelCase_ :      Union[str, Any]    				=				outputs.hidden_states

              lowerCAmelCase_ :      Optional[int]    				=				2_6
              self.assertEqual(len(UpperCamelCase__							)   ,						UpperCamelCase__							)

          lowerCAmelCase_ :      Tuple    				=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              lowerCAmelCase_ :      List[str]    				=				True
              check_hidden_states_output(UpperCamelCase__   ,						UpperCamelCase__   ,						UpperCamelCase__							)

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

              check_hidden_states_output(UpperCamelCase__   ,						UpperCamelCase__   ,						UpperCamelCase__							)




      def 						lowercase_ (				self							)					->    Tuple:
          lowerCAmelCase_ :      str    				=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__							)




      @slow
      def 						lowercase_ (				self							)					->    Any:
          for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              lowerCAmelCase_ :      Optional[int]    				=				MobileNetVaModel.from_pretrained(UpperCamelCase__							)
              self.assertIsNotNone(UpperCamelCase__							)






def 			lowerCAmelCase (		)-> Tuple:
    lowerCAmelCase_ :      Union[str, 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 						lowercase_ (				self							)					->    List[Any]:
          return (
              MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224'''							) if is_vision_available() else None
          )




      @slow
      def 						lowercase_ (				self							)					->    str:
          lowerCAmelCase_ :      Optional[int]    				=				MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224'''							).to(UpperCamelCase__							)

          lowerCAmelCase_ :      Optional[int]    				=				self.default_image_processor
          lowerCAmelCase_ :      Optional[int]    				=				prepare_img()
          lowerCAmelCase_ :      int    				=				image_processor(images=UpperCamelCase__   ,						return_tensors='''pt'''							).to(UpperCamelCase__							)

          # forward pass
          with torch.no_grad():
              lowerCAmelCase_ :      List[str]    				=				model(**UpperCamelCase__							)

          # verify the logits
          lowerCAmelCase_ :      Union[str, Any]    				=				torch.Size((1, 1_0_0_1)							)
          self.assertEqual(outputs.logits.shape   ,						UpperCamelCase__							)

          lowerCAmelCase_ :      List[str]    				=				torch.tensor([-4.17_39, -1.12_33, 3.12_05]							).to(UpperCamelCase__							)

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



import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_UpperCAmelCase			:  str     =logging.get_logger(__name__)







class 				snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  Optional[int]					=							"""encoder-decoder"""
						SCREAMING_SNAKE_CASE__      :  str					=							True




						def __init__(				self   ,						**__lowercase							)					->    Union[str, Any]:
										super().__init__(**__lowercase							)
										assert (
										    "encoder" in kwargs and "decoder" in kwargs
										), "Config has to be initialized with encoder and decoder config"
										lowerCAmelCase_ :      str    				=				kwargs.pop('''encoder'''							)
										lowerCAmelCase_ :      int    				=				encoder_config.pop('''model_type'''							)
										lowerCAmelCase_ :      Optional[Any]    				=				kwargs.pop('''decoder'''							)
										lowerCAmelCase_ :      Optional[Any]    				=				decoder_config.pop('''model_type'''							)

										from ..auto.configuration_auto import AutoConfig

										lowerCAmelCase_ :      Union[str, Any]    				=				AutoConfig.for_model(__lowercase   ,						**__lowercase							)
										lowerCAmelCase_ :      List[str]    				=				AutoConfig.for_model(__lowercase   ,						**__lowercase							)
										lowerCAmelCase_ :      Any    				=				True




						@classmethod
						def 						lowercase_ (				cls   ,						__lowercase   ,						__lowercase   ,						**__lowercase							)					->    PretrainedConfig:
										logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'''							)
										lowerCAmelCase_ :      int    				=				True
										lowerCAmelCase_ :      List[Any]    				=				True

										return cls(encoder=encoder_config.to_dict()   ,						decoder=decoder_config.to_dict()   ,						**__lowercase							)




						def 						lowercase_ (				self							)					->    Any:
										lowerCAmelCase_ :      Optional[Any]    				=				copy.deepcopy(self.__dict__							)
										lowerCAmelCase_ :      List[str]    				=				self.encoder.to_dict()
										lowerCAmelCase_ :      Dict    				=				self.decoder.to_dict()
										lowerCAmelCase_ :      Optional[Any]    				=				self.__class__.model_type
										return output