





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 					A__       (				__UpperCAmelCase      ):




   """simple docstring"""



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







          '''simple docstring'''

          a__		:      Optional[Any]					=							self.config_class(**self.inputs_dict)
          self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_   ,    'tf_padding'))
          self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_   ,    'depth_multiplier'))





class 					A__       :




   """simple docstring"""



   def __init__(   self   ,    lowercase   ,    lowercase=13   ,    lowercase=3   ,    lowercase=32   ,    lowercase=0.25   ,    lowercase=8   ,    lowercase=8   ,    lowercase=6   ,    lowercase=32   ,    lowercase=True   ,    lowercase=True   ,    lowercase=True   ,    lowercase="relu6"   ,    lowercase=1280   ,    lowercase=0.1   ,    lowercase=0.02   ,    lowercase=True   ,    lowercase=True   ,    lowercase=10   ,    lowercase=None   ,    )     ->		Union[str, Any]:







          '''simple docstring'''

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

   def 				__lowercase						(   self)     ->		str:







          '''simple docstring'''

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

          a__		:      Optional[Any]					=							None
          a__		:      Any					=							None
          if self.use_labels:
                 a__		:      Union[str, Any]					=							ids_tensor([self.batch_size]   ,    self.num_labels)
                 a__		:      List[Any]					=							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   ,    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 				__lowercase						(   self   ,    lowercase   ,    lowercase   ,    lowercase   ,    lowercase)     ->		str:







          '''simple docstring'''

          a__		:      Optional[int]					=							MobileNetVaModel(config=SCREAMING_SNAKE_CASE_)
          model.to(SCREAMING_SNAKE_CASE_)
          model.eval()
          a__		:      List[Any]					=							model(SCREAMING_SNAKE_CASE_)
          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 				__lowercase						(   self   ,    lowercase   ,    lowercase   ,    lowercase   ,    lowercase)     ->		List[str]:







          '''simple docstring'''

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

   def 				__lowercase						(   self   ,    lowercase   ,    lowercase   ,    lowercase   ,    lowercase)     ->		Dict:







          '''simple docstring'''

          a__		:      Optional[int]					=							self.num_labels
          a__		:      Optional[Any]					=							MobileNetVaForSemanticSegmentation(SCREAMING_SNAKE_CASE_)
          model.to(SCREAMING_SNAKE_CASE_)
          model.eval()
          a__		:      Any					=							model(SCREAMING_SNAKE_CASE_)
          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__		:      int					=							model(SCREAMING_SNAKE_CASE_   ,    labels=SCREAMING_SNAKE_CASE_)
          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 				__lowercase						(   self)     ->		Dict:







          '''simple docstring'''

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





@require_torch
class 					A__       (				__UpperCAmelCase					,    __UpperCAmelCase					,    unittest.TestCase      ):




   """simple docstring"""



   __A  :							List[str]			    =    (
       (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   __A  :							Optional[Any]			    =    (
       {
           'feature-extraction': MobileNetVaModel,
           'image-classification': MobileNetVaForImageClassification,
           'image-segmentation': MobileNetVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A  :							Optional[Any]			    =    False
   __A  :							List[str]			    =    False
   __A  :							List[Any]			    =    False
   __A  :							Any			    =    False

   def 				__lowercase						(   self)     ->		str:







          '''simple docstring'''

          a__		:      Optional[int]					=							MobileNetVaModelTester(self)
          a__		:      Any					=							MobileNetVaConfigTester(self   ,    config_class=SCREAMING_SNAKE_CASE_   ,    has_text_modality=SCREAMING_SNAKE_CASE_)

   def 				__lowercase						(   self)     ->		List[Any]:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='MobileNetV2 does not use inputs_embeds')
   def 				__lowercase						(   self)     ->		str:







          '''simple docstring'''

          pass

   @unittest.skip(reason='MobileNetV2 does not support input and output embeddings')
   def 				__lowercase						(   self)     ->		Any:







          '''simple docstring'''

          pass

   @unittest.skip(reason='MobileNetV2 does not output attentions')
   def 				__lowercase						(   self)     ->		Optional[Any]:







          '''simple docstring'''

          pass

   def 				__lowercase						(   self)     ->		int:







          '''simple docstring'''

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

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

                 a__		:      Union[str, Any]					=							['pixel_values']
                 self.assertListEqual(arg_names[:1]   ,    SCREAMING_SNAKE_CASE_)

   def 				__lowercase						(   self)     ->		List[Any]:







          '''simple docstring'''

          a__		:      str					=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_)

   def 				__lowercase						(   self)     ->		List[Any]:







          '''simple docstring'''

          def check_hidden_states_output(lowercase   ,    lowercase   ,    lowercase):
                 a__		:      Dict					=							model_class(SCREAMING_SNAKE_CASE_)
                 model.to(SCREAMING_SNAKE_CASE_)
                 model.eval()

                 with torch.no_grad():
                        a__		:      Tuple					=							model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_))

                 a__		:      List[str]					=							outputs.hidden_states

                 a__		:      List[Any]					=							16
                 self.assertEqual(len(SCREAMING_SNAKE_CASE_)   ,    SCREAMING_SNAKE_CASE_)

          a__					,				a__		:      Tuple					=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__		:      Any					=							True
                 check_hidden_states_output(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_)

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

                 check_hidden_states_output(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_)

   def 				__lowercase						(   self)     ->		List[Any]:







          '''simple docstring'''

          a__		:      Optional[int]					=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_)

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







          '''simple docstring'''

          a__		:      Any					=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_)

   @slow
   def 				__lowercase						(   self)     ->		Optional[int]:







          '''simple docstring'''

          for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__		:      Any					=							MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE_)
                 self.assertIsNotNone(SCREAMING_SNAKE_CASE_)



def A_      (						)    ->						List[str]:
       a__		:      List[Any]					=							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
       return image





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




   """simple docstring"""



   @cached_property
   def 				__lowercase						(   self)     ->		List[Any]:







          '''simple docstring'''

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

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







          '''simple docstring'''

          a__		:      int					=							MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224').to(SCREAMING_SNAKE_CASE_)

          a__		:      Tuple					=							self.default_image_processor
          a__		:      int					=							prepare_img()
          a__		:      Dict					=							image_processor(images=SCREAMING_SNAKE_CASE_   ,    return_tensors='pt').to(SCREAMING_SNAKE_CASE_)

          # forward pass
          with torch.no_grad():
                 a__		:      Tuple					=							model(**SCREAMING_SNAKE_CASE_)

          # verify the logits
          a__		:      Dict					=							torch.Size((1, 1001))
          self.assertEqual(outputs.logits.shape   ,    SCREAMING_SNAKE_CASE_)

          a__		:      List[str]					=							torch.tensor([0.24_45, -1.19_93, 0.19_05]).to(SCREAMING_SNAKE_CASE_)

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

   @slow
   def 				__lowercase						(   self)     ->		Union[str, Any]:







          '''simple docstring'''

          a__		:      List[Any]					=							MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513')
          a__		:      List[str]					=							model.to(SCREAMING_SNAKE_CASE_)

          a__		:      int					=							MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513')

          a__		:      str					=							prepare_img()
          a__		:      Tuple					=							image_processor(images=SCREAMING_SNAKE_CASE_   ,    return_tensors='pt').to(SCREAMING_SNAKE_CASE_)

          # forward pass
          with torch.no_grad():
                 a__		:      List[str]					=							model(**SCREAMING_SNAKE_CASE_)
          a__		:      Optional[int]					=							outputs.logits

          # verify the logits
          a__		:      Union[str, Any]					=							torch.Size((1, 21, 65, 65))
          self.assertEqual(logits.shape   ,    SCREAMING_SNAKE_CASE_)

          a__		:      str					=							torch.tensor(
              [
                  [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
                  [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
                  [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
              ]   ,    device=SCREAMING_SNAKE_CASE_   ,    )

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




from __future__ import annotations

__a         =   8.988E9  # units = N * m^s * C^-2




def 							a		(				snake_case__:   float		,  snake_case__:   float		,  snake_case__:   float		,  snake_case__:   float   ):


				'''simple docstring'''
				lowercase_	    =   abs(chargea * chargea   )

				if (force, chargea, chargea, distance).count(0   ) != 1:
								raise ValueError('''One and only one argument must be 0'''   )
				if distance < 0:
								raise ValueError('''Distance cannot be negative'''   )
				if force == 0:
								lowercase_	    =   COULOMBS_CONSTANT * charge_product / (distance**2)
								return {"force": force}
				elif chargea == 0:
								lowercase_	    =   abs(snake_case__   ) * (distance**2) / (COULOMBS_CONSTANT * chargea)
								return {"charge1": chargea}
				elif chargea == 0:
								lowercase_	    =   abs(snake_case__   ) * (distance**2) / (COULOMBS_CONSTANT * chargea)
								return {"charge2": chargea}
				elif distance == 0:
								lowercase_	    =   (COULOMBS_CONSTANT * charge_product / abs(snake_case__   )) ** 0.5
								return {"distance": distance}
				raise ValueError('''Exactly one argument must be 0'''   )


if __name__ == "__main__":
						import doctest

						doctest.testmod()




