






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    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_									=     self.config_class(**self.inputs_dict )
     self.parent.assertTrue(hasattr(_UpperCAmelCase		,		'tf_padding' ) )
     self.parent.assertTrue(hasattr(_UpperCAmelCase		,		'depth_multiplier' ) )




class 						_a       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=3		,		_UpperCAmelCase=32		,		_UpperCAmelCase=0.2_5		,		_UpperCAmelCase=8		,		_UpperCAmelCase=8		,		_UpperCAmelCase=6		,		_UpperCAmelCase=32		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase="relu6"		,		_UpperCAmelCase=1280		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=10		,		_UpperCAmelCase=None		,		)			-> Union[str, Any]:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     image_size
     UpperCamelCase_									=     depth_multiplier
     UpperCamelCase_									=     depth_divisible_by
     UpperCamelCase_									=     min_depth
     UpperCamelCase_									=     expand_ratio
     UpperCamelCase_									=     tf_padding
     UpperCamelCase_									=     output_stride
     UpperCamelCase_									=     first_layer_is_expansion
     UpperCamelCase_									=     finegrained_output
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier )
     UpperCamelCase_									=     classifier_dropout_prob
     UpperCamelCase_									=     use_labels
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     num_labels
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     scope




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     UpperCamelCase_									=     None
     UpperCamelCase_									=     None
     if self.use_labels:
        UpperCamelCase_									=     ids_tensor([self.batch_size]		,		self.num_labels )
        UpperCamelCase_									=     ids_tensor([self.batch_size, self.image_size, self.image_size]		,		self.num_labels )

     UpperCamelCase_									=     self.get_config()

     return config, pixel_values, labels, pixel_labels




  def    _UpperCAmelCase     (     self )			-> Optional[int]:
     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    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Union[str, Any]:
     UpperCamelCase_									=     MobileNetVaModel(config=_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     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,
         )		,		)
     self.parent.assertEqual(
         result.pooler_output.shape		,		(self.batch_size, self.last_hidden_size)		,		)




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




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> str:
     UpperCamelCase_									=     self.num_labels
     UpperCamelCase_									=     MobileNetVaForSemanticSegmentation(_UpperCAmelCase )
     model.to(_UpperCAmelCase )
     model.eval()
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(
         result.logits.shape		,		(
             self.batch_size,
             self.num_labels,
             self.image_size // self.output_stride,
             self.image_size // self.output_stride,
         )		,		)
     UpperCamelCase_									=     model(_UpperCAmelCase		,		labels=_UpperCAmelCase )
     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    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     config_and_inputs
     UpperCamelCase_									=     {'pixel_values': pixel_values}
     return config, inputs_dict




@require_torch
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





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

  A_						=   False
  A_						=   False
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     MobileNetVaModelTester(self )
     UpperCamelCase_									=     MobileNetVaConfigTester(self		,		config_class=_UpperCAmelCase		,		has_text_modality=_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> str:
     self.config_tester.run_common_tests()




  @unittest.skip(reason='MobileNetV2 does not use inputs_embeds' )
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     pass




  @unittest.skip(reason='MobileNetV2 does not support input and output embeddings' )
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     pass




  @unittest.skip(reason='MobileNetV2 does not output attentions' )
  def    _UpperCAmelCase     (     self )			-> List[str]:
     pass




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase_									=     ['pixel_values']
        self.assertListEqual(arg_names[:1]		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> str:
     def check_hidden_states_output(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase ):
        UpperCamelCase_									=     model_class(_UpperCAmelCase )
        model.to(_UpperCAmelCase )
        model.eval()

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

        UpperCamelCase_									=     outputs.hidden_states

        UpperCamelCase_									=     16
        self.assertEqual(len(_UpperCAmelCase )		,		_UpperCAmelCase )

     UpperCamelCase_		,      UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs_for_common()

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

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        UpperCamelCase_									=     True

        check_hidden_states_output(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> Optional[int]:
     for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase_									=     MobileNetVaModel.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )






def     _snake_case    ():
   UpperCamelCase_									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
   return image


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






  """simple docstring"""





  @cached_property
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     return (
         MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224' ) if is_vision_available() else None
     )




  @slow
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224' ).to(_UpperCAmelCase )

     UpperCamelCase_									=     self.default_image_processor
     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' ).to(_UpperCAmelCase )

     # forward pass
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )

     # verify the logits
     UpperCamelCase_									=     torch.Size((1, 1001) )
     self.assertEqual(outputs.logits.shape		,		_UpperCAmelCase )

     UpperCamelCase_									=     torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5] ).to(_UpperCAmelCase )

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




  @slow
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' )
     UpperCamelCase_									=     model.to(_UpperCAmelCase )

     UpperCamelCase_									=     MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' )

     UpperCamelCase_									=     prepare_img()
     UpperCamelCase_									=     image_processor(images=_UpperCAmelCase		,		return_tensors='pt' ).to(_UpperCAmelCase )

     # forward pass
     with torch.no_grad():
        UpperCamelCase_									=     model(**_UpperCAmelCase )
     UpperCamelCase_									=     outputs.logits

     # verify the logits
     UpperCamelCase_									=     torch.Size((1, 21, 65, 65) )
     self.assertEqual(logits.shape		,		_UpperCAmelCase )

     UpperCamelCase_									=     torch.tensor(
         [
             [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
             [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
             [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
         ]		,		device=_UpperCAmelCase		,		)

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













def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase):
   return not any(
       neighbour == 1 and colored_vertices[i] == color
       for i, neighbour in enumerate(__lowercase))






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase):

   # Base Case
   if index == len(__lowercase):
      return True

   # Recursive Step
   for i in range(__lowercase):
      if valid_coloring(graph[index]    ,      __lowercase    ,      __lowercase):
         # Color current vertex
         UpperCamelCase_									=     i
         # Validate coloring
         if util_color(__lowercase    ,      __lowercase    ,      __lowercase    ,      index + 1):
            return True
         # Backtrack
         UpperCamelCase_									=     -1
   return False






def     _snake_case    (__lowercase    ,      __lowercase):
   UpperCamelCase_									=     [-1] * len(__lowercase)

   if util_color(__lowercase    ,      __lowercase    ,      __lowercase    ,      0):
      return colored_vertices

   return []





