


"""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       SCREAMING_SNAKE_CASE__				(		__snake_case				):
       """simple docstring"""


       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     List[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       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


       def __init__(						self		,     snake_case__		,     snake_case__=13		,     snake_case__=3		,     snake_case__=32		,     snake_case__=0.25		,     snake_case__=8		,     snake_case__=8		,     snake_case__=6		,     snake_case__=32		,     snake_case__=True		,     snake_case__=True		,     snake_case__=True		,     snake_case__="relu6"		,     snake_case__=1_280		,     snake_case__=0.1		,     snake_case__=0.02		,     snake_case__=True		,     snake_case__=True		,     snake_case__=10		,     snake_case__=None		,     ):






         """simple docstring"""





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

       def        lowercase__							(						self						):






         """simple docstring"""





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

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

         lowerCAmelCase     :     int								=							self.get_config()

         return config, pixel_values, labels, pixel_labels

       def        lowercase__							(						self						):






         """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		,     snake_case__		,     snake_case__		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Tuple								=							MobileNetVaModel(config=__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()
         lowerCAmelCase     :     int								=							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		,     snake_case__		,     snake_case__		,     snake_case__		,     snake_case__						):






         """simple docstring"""





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

       def        lowercase__							(						self		,     snake_case__		,     snake_case__		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Optional[Any]								=							self.num_labels
         lowerCAmelCase     :     Dict								=							MobileNetVaForSemanticSegmentation(__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()
         lowerCAmelCase     :     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,
             )		,     )
         lowerCAmelCase     :     Union[str, Any]								=							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						):






         """simple docstring"""





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


@require_torch
class       SCREAMING_SNAKE_CASE__				(		__snake_case   ,    __snake_case   ,    unittest.TestCase				):
       """simple docstring"""


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

       a  :				str   =False
       a  :				str   =False
       a  :				Any   =False
       a  :				Optional[Any]   =False

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Any								=							MobileNetVaModelTester(self						)
         lowerCAmelCase     :     List[Any]								=							MobileNetVaConfigTester(self		,     config_class=__SCREAMING_SNAKE_CASE		,     has_text_modality=__SCREAMING_SNAKE_CASE						)

       def        lowercase__							(						self						):






         """simple docstring"""





         self.config_tester.run_common_tests()

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






         """simple docstring"""





         pass

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






         """simple docstring"""





         pass

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






         """simple docstring"""





         pass

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase						,  lowerCAmelCase     :     List[Any]								=							self.model_tester.prepare_config_and_inputs_for_common()

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

           lowerCAmelCase     :     List[str]								=							["pixel_values"]
           self.assertListEqual(arg_names[:1]		,     __SCREAMING_SNAKE_CASE						)

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     int								=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE						)

       def        lowercase__							(						self						):






         """simple docstring"""





         def check_hidden_states_output(snake_case__		,     snake_case__		,     snake_case__						):
           lowerCAmelCase     :     Dict								=							model_class(__SCREAMING_SNAKE_CASE						)
           model.to(__SCREAMING_SNAKE_CASE						)
           model.eval()

           with torch.no_grad():
             lowerCAmelCase     :     Dict								=							model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE		,     __SCREAMING_SNAKE_CASE						)						)

           lowerCAmelCase     :     int								=							outputs.hidden_states

           lowerCAmelCase     :     str								=							16
           self.assertEqual(len(__SCREAMING_SNAKE_CASE						)		,     __SCREAMING_SNAKE_CASE						)

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

         for model_class in self.all_model_classes:
           lowerCAmelCase     :     Optional[int]								=							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"]
           lowerCAmelCase     :     List[Any]								=							True

           check_hidden_states_output(__SCREAMING_SNAKE_CASE		,     __SCREAMING_SNAKE_CASE		,     __SCREAMING_SNAKE_CASE						)

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Dict								=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE						)

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Optional[int]								=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE						)







       @slow
       def        lowercase__							(						self						):






         """simple docstring"""





         for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowerCAmelCase     :     Union[str, Any]								=							MobileNetVaModel.from_pretrained(__SCREAMING_SNAKE_CASE						)
           self.assertIsNotNone(__SCREAMING_SNAKE_CASE						)

def 					a__			(				):


  '''simple docstring'''







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





@require_torch
@require_vision
class       SCREAMING_SNAKE_CASE__				(		unittest.TestCase				):
       """simple docstring"""


       @cached_property
       def        lowercase__							(						self						):






         """simple docstring"""





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

       @slow
       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Dict								=							MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"						).to(__SCREAMING_SNAKE_CASE						)

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

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

         # verify the logits
         lowerCAmelCase     :     List[str]								=							torch.Size((1, 1_001)						)
         self.assertEqual(outputs.logits.shape		,     __SCREAMING_SNAKE_CASE						)

         lowerCAmelCase     :     Any								=							torch.tensor([0.2445, -1.1993, 0.1905]						).to(__SCREAMING_SNAKE_CASE						)

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







       @slow
       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     List[Any]								=							MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"						)
         lowerCAmelCase     :     Tuple								=							model.to(__SCREAMING_SNAKE_CASE						)

         lowerCAmelCase     :     Union[str, Any]								=							MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"						)

         lowerCAmelCase     :     Any								=							prepare_img()
         lowerCAmelCase     :     str								=							image_processor(images=__SCREAMING_SNAKE_CASE		,     return_tensors="pt"						).to(__SCREAMING_SNAKE_CASE						)

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

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

         lowerCAmelCase     :     int								=							torch.tensor(
             [
                 [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
                 [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
                 [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
             ]		,     device=__SCREAMING_SNAKE_CASE		,     )

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













"""simple docstring"""





from math import pow, sqrt







def      lowerCamelCase__       (							*_lowerCamelCase       :		float )      ->				bool:
  lowerCamelCase_         =						len(_lowerCamelCase ) > 0 and all(value > 0.0 for value in values )
  return result







def      lowerCamelCase__       (							_lowerCamelCase       :		float		,				_lowerCamelCase       :		float )      ->				float | ValueError:
  return (
      round(sqrt(molar_mass_a / molar_mass_a )		,				6 )
      if validate(_lowerCamelCase		,				_lowerCamelCase )
      else ValueError('Input Error: Molar mass values must greater than 0.' )
  )







def      lowerCamelCase__       (							_lowerCamelCase       :		float		,				_lowerCamelCase       :		float		,				_lowerCamelCase       :		float )      ->				float | ValueError:
  return (
      round(effusion_rate * sqrt(molar_mass_a / molar_mass_a )		,				6 )
      if validate(_lowerCamelCase		,				_lowerCamelCase		,				_lowerCamelCase )
      else ValueError(
          'Input Error: Molar mass and effusion rate values must greater than 0.' )
  )







def      lowerCamelCase__       (							_lowerCamelCase       :		float		,				_lowerCamelCase       :		float		,				_lowerCamelCase       :		float )      ->				float | ValueError:
  return (
      round(effusion_rate / sqrt(molar_mass_a / molar_mass_a )		,				6 )
      if validate(_lowerCamelCase		,				_lowerCamelCase		,				_lowerCamelCase )
      else ValueError(
          'Input Error: Molar mass and effusion rate values must greater than 0.' )
  )







def      lowerCamelCase__       (							_lowerCamelCase       :		float		,				_lowerCamelCase       :		float		,				_lowerCamelCase       :		float )      ->				float | ValueError:
  return (
      round(molar_mass / pow(effusion_rate_a / effusion_rate_a		,				2 )		,				6 )
      if validate(_lowerCamelCase		,				_lowerCamelCase		,				_lowerCamelCase )
      else ValueError(
          'Input Error: Molar mass and effusion rate values must greater than 0.' )
  )







def      lowerCamelCase__       (							_lowerCamelCase       :		float		,				_lowerCamelCase       :		float		,				_lowerCamelCase       :		float )      ->				float | ValueError:
  return (
      round(pow(effusion_rate_a / effusion_rate_a		,				2 ) / molar_mass		,				6 )
      if validate(_lowerCamelCase		,				_lowerCamelCase		,				_lowerCamelCase )
      else ValueError(
          'Input Error: Molar mass and effusion rate values must greater than 0.' )
  )




