





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 				__lowerCAmelCase       (    UpperCamelCase__):







      def    _lowercase  (    self							)   ->						Optional[Any]:



        '''simple docstring'''




        a__	:					Optional[int]										=self.config_class(**self.inputs_dict							)
        self.parent.assertTrue(hasattr(lowerCAmelCase__		,      "tf_padding"							)							)
        self.parent.assertTrue(hasattr(lowerCAmelCase__		,      "depth_multiplier"							)							)







class 				__lowerCAmelCase       :







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__=1_3		,      lowerCAmelCase__=3		,      lowerCAmelCase__=3_2		,      lowerCAmelCase__=0.25		,      lowerCAmelCase__=8		,      lowerCAmelCase__=True		,      lowerCAmelCase__=1_0_2_4		,      lowerCAmelCase__=3_2		,      lowerCAmelCase__="relu6"		,      lowerCAmelCase__=0.1		,      lowerCAmelCase__=0.02		,      lowerCAmelCase__=True		,      lowerCAmelCase__=True		,      lowerCAmelCase__=1_0		,      lowerCAmelCase__=None		,      )   ->						Optional[int]:



        '''simple docstring'''




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







      def    _lowercase  (    self							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Union[str, Any]										=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

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

        return config, pixel_values, labels, pixel_labels







      def    _lowercase  (    self							)   ->						Tuple:



        '''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    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)   ->						str:



        '''simple docstring'''




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







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)   ->						Tuple:



        '''simple docstring'''




        a__	:					Tuple										=self.num_labels
        a__	:					Optional[int]										=MobileNetVaForImageClassification(lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__	:					Optional[int]										=model(lowerCAmelCase__		,      labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)							)







      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        a__	:					str										=self.prepare_config_and_inputs()
        a__					,							a__					,							a__					,							a__	:					List[Any]										=config_and_inputs
        a__	:					int										={"pixel_values": pixel_values}
        return config, inputs_dict







@require_torch
class 				__lowerCAmelCase       (    UpperCamelCase__						,				UpperCamelCase__						,				unittest.TestCase):
      _lowercase				:					Any						=			(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
      _lowercase				:					str						=			(
          {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
          if is_torch_available()
          else {}
      )

      _lowercase				:					Tuple						=			False
      _lowercase				:					int						=			False
      _lowercase				:					Tuple						=			False
      _lowercase				:					List[str]						=			False







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        a__	:					str										=MobileNetVaModelTester(self							)
        a__	:					Optional[Any]										=MobileNetVaConfigTester(self		,      config_class=lowerCAmelCase__		,      has_text_modality=lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						Union[str, Any]:



        '''simple docstring'''




        self.config_tester.run_common_tests()







      @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"							)
      def    _lowercase  (    self							)   ->						Optional[Any]:



        '''simple docstring'''




        pass







      @unittest.skip(reason="MobileNetV1 does not support input and output embeddings"							)
      def    _lowercase  (    self							)   ->						List[str]:



        '''simple docstring'''




        pass







      @unittest.skip(reason="MobileNetV1 does not output attentions"							)
      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




        pass







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




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

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

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







      def    _lowercase  (    self							)   ->						Tuple:



        '''simple docstring'''




        a__	:					Tuple										=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




        def check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							):
          a__	:					str										=model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()

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

          a__	:					Optional[int]										=outputs.hidden_states

          a__	:					Optional[Any]										=2_6
          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__	:					List[str]										=True

          check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        a__	:					List[Any]										=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__							)







      @slow
      def    _lowercase  (    self							)   ->						List[str]:



        '''simple docstring'''




        for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__	:					List[Any]										=MobileNetVaModel.from_pretrained(lowerCAmelCase__							)
          self.assertIsNotNone(lowerCAmelCase__							)
def      _A       (		):





  """simple docstring"""



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







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







      @cached_property
      def    _lowercase  (    self							)   ->						Optional[int]:



        '''simple docstring'''




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







      @slow
      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        a__	:					Union[str, Any]										=MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"							).to(lowerCAmelCase__							)

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

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

        # verify the logits
        a__	:					Any										=torch.Size((1, 1_0_0_1)							)
        self.assertEqual(outputs.logits.shape		,      lowerCAmelCase__							)

        a__	:					int										=torch.tensor([-4.17_39, -1.12_33, 3.12_05]							).to(lowerCAmelCase__							)

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













import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import MobileNetVaImageProcessor







class 				__lowerCAmelCase       (    unittest.TestCase):







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__=7		,      lowerCAmelCase__=3		,      lowerCAmelCase__=1_8		,      lowerCAmelCase__=3_0		,      lowerCAmelCase__=4_0_0		,      lowerCAmelCase__=True		,      lowerCAmelCase__=None		,      lowerCAmelCase__=True		,      lowerCAmelCase__=None		,      )   ->						Optional[int]:



        '''simple docstring'''




        a__	:					str										=size if size is not None else {"shortest_edge": 2_0}
        a__	:					Union[str, Any]										=crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
        a__	:					Tuple										=parent
        a__	:					Optional[int]										=batch_size
        a__	:					Any										=num_channels
        a__	:					List[str]										=image_size
        a__	:					Dict										=min_resolution
        a__	:					List[Any]										=max_resolution
        a__	:					Dict										=do_resize
        a__	:					Union[str, Any]										=size
        a__	:					str										=do_center_crop
        a__	:					List[str]										=crop_size







      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
        }







@require_torch
@require_vision
class 				__lowerCAmelCase       (    UpperCamelCase__						,				unittest.TestCase):
      _lowercase				:					Optional[Any]						=			MobileNetVaImageProcessor if is_vision_available() else None







      def    _lowercase  (    self							)   ->						Tuple:



        '''simple docstring'''




        a__	:					Optional[int]										=MobileNetVaImageProcessingTester(self							)







      @property
      def    _lowercase  (    self							)   ->						List[str]:



        '''simple docstring'''




        return self.image_processor_tester.prepare_image_processor_dict()







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        a__	:					List[str]										=self.image_processing_class(**self.image_processor_dict							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "do_resize"							)							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "size"							)							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "do_center_crop"							)							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "crop_size"							)							)







      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




        a__	:					Any										=self.image_processing_class.from_dict(self.image_processor_dict							)
        self.assertEqual(image_processor.size		,      {"shortest_edge": 2_0}							)
        self.assertEqual(image_processor.crop_size		,      {"height": 1_8, "width": 1_8}							)

        a__	:					Dict										=self.image_processing_class.from_dict(self.image_processor_dict		,      size=4_2		,      crop_size=8_4							)
        self.assertEqual(image_processor.size		,      {"shortest_edge": 4_2}							)
        self.assertEqual(image_processor.crop_size		,      {"height": 8_4, "width": 8_4}							)







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        pass







      def    _lowercase  (    self							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Dict										=self.image_processing_class(**self.image_processor_dict							)
        # create random PIL images
        a__	:					Optional[Any]										=prepare_image_inputs(self.image_processor_tester		,      equal_resolution=lowerCAmelCase__							)
        for image in image_inputs:
          self.assertIsInstance(lowerCAmelCase__		,      Image.Image							)

        # Test not batched input
        a__	:					List[Any]										=image_processing(image_inputs[0]		,      return_tensors="pt"							).pixel_values
        self.assertEqual(
            encoded_images.shape		,      (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["height"],
                self.image_processor_tester.crop_size["width"],
            )		,      )

        # Test batched
        a__	:					Dict										=image_processing(lowerCAmelCase__		,      return_tensors="pt"							).pixel_values
        self.assertEqual(
            encoded_images.shape		,      (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["height"],
                self.image_processor_tester.crop_size["width"],
            )		,      )







      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        a__	:					str										=self.image_processing_class(**self.image_processor_dict							)
        # create random numpy tensors
        a__	:					str										=prepare_image_inputs(self.image_processor_tester		,      equal_resolution=lowerCAmelCase__		,      numpify=lowerCAmelCase__							)
        for image in image_inputs:
          self.assertIsInstance(lowerCAmelCase__		,      np.ndarray							)

        # Test not batched input
        a__	:					List[str]										=image_processing(image_inputs[0]		,      return_tensors="pt"							).pixel_values
        self.assertEqual(
            encoded_images.shape		,      (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["height"],
                self.image_processor_tester.crop_size["width"],
            )		,      )

        # Test batched
        a__	:					Union[str, Any]										=image_processing(lowerCAmelCase__		,      return_tensors="pt"							).pixel_values
        self.assertEqual(
            encoded_images.shape		,      (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["height"],
                self.image_processor_tester.crop_size["width"],
            )		,      )







      def    _lowercase  (    self							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Any										=self.image_processing_class(**self.image_processor_dict							)
        # create random PyTorch tensors
        a__	:					int										=prepare_image_inputs(self.image_processor_tester		,      equal_resolution=lowerCAmelCase__		,      torchify=lowerCAmelCase__							)
        for image in image_inputs:
          self.assertIsInstance(lowerCAmelCase__		,      torch.Tensor							)

        # Test not batched input
        a__	:					Optional[Any]										=image_processing(image_inputs[0]		,      return_tensors="pt"							).pixel_values
        self.assertEqual(
            encoded_images.shape		,      (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["height"],
                self.image_processor_tester.crop_size["width"],
            )		,      )

        # Test batched
        a__	:					str										=image_processing(lowerCAmelCase__		,      return_tensors="pt"							).pixel_values
        self.assertEqual(
            encoded_images.shape		,      (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["height"],
                self.image_processor_tester.crop_size["width"],
            )		,      )






