




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 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 def  lowerCAmelCase_    (				self    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     self.config_class(**self.inputs_dict		)
       self.parent.assertTrue(hasattr(_lowerCAmelCase							,							'tf_padding'		)		)
       self.parent.assertTrue(hasattr(_lowerCAmelCase							,							'depth_multiplier'		)		)





class 			lowerCamelCase_				:


 '''simple docstring'''







 def __init__(				self    :						Dict							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						List[Any]=13							,							_lowerCAmelCase    :						Optional[Any]=3							,							_lowerCAmelCase    :						Optional[int]=32							,							_lowerCAmelCase    :						Dict=0.25							,							_lowerCAmelCase    :						str=8							,							_lowerCAmelCase    :						Dict=8							,							_lowerCAmelCase    :						Union[str, Any]=6							,							_lowerCAmelCase    :						str=32							,							_lowerCAmelCase    :						int=True							,							_lowerCAmelCase    :						Dict=True							,							_lowerCAmelCase    :						Optional[int]=True							,							_lowerCAmelCase    :						Tuple="relu6"							,							_lowerCAmelCase    :						Optional[int]=1_280							,							_lowerCAmelCase    :						Union[str, Any]=0.1							,							_lowerCAmelCase    :						Any=0.02							,							_lowerCAmelCase    :						int=True							,							_lowerCAmelCase    :						Dict=True							,							_lowerCAmelCase    :						Union[str, Any]=10							,							_lowerCAmelCase    :						Optional[Any]=None							,							):
       SCREAMING_SNAKE_CASE_      		=     parent
       SCREAMING_SNAKE_CASE_      		=     batch_size
       SCREAMING_SNAKE_CASE_      		=     num_channels
       SCREAMING_SNAKE_CASE_      		=     image_size
       SCREAMING_SNAKE_CASE_      		=     depth_multiplier
       SCREAMING_SNAKE_CASE_      		=     depth_divisible_by
       SCREAMING_SNAKE_CASE_      		=     min_depth
       SCREAMING_SNAKE_CASE_      		=     expand_ratio
       SCREAMING_SNAKE_CASE_      		=     tf_padding
       SCREAMING_SNAKE_CASE_      		=     output_stride
       SCREAMING_SNAKE_CASE_      		=     first_layer_is_expansion
       SCREAMING_SNAKE_CASE_      		=     finegrained_output
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier		)
       SCREAMING_SNAKE_CASE_      		=     classifier_dropout_prob
       SCREAMING_SNAKE_CASE_      		=     use_labels
       SCREAMING_SNAKE_CASE_      		=     is_training
       SCREAMING_SNAKE_CASE_      		=     num_labels
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     scope



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

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

       SCREAMING_SNAKE_CASE_      		=     self.get_config()

       return config, pixel_values, labels, pixel_labels



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



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



 def  lowerCAmelCase_    (				self    :						List[Any]							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						Dict							,							_lowerCAmelCase    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     self.num_labels
       SCREAMING_SNAKE_CASE_      		=     MobileNetVaForSemanticSegmentation(_lowerCAmelCase		)
       model.to(_lowerCAmelCase		)
       model.eval()
       SCREAMING_SNAKE_CASE_      		=     model(_lowerCAmelCase		)
       self.parent.assertEqual(
           result.logits.shape							,							(
               self.batch_size,
               self.num_labels,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )							,							)
       SCREAMING_SNAKE_CASE_      		=     model(_lowerCAmelCase							,							labels=_lowerCAmelCase		)
       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  lowerCAmelCase_    (				self    :						List[str]		):
       SCREAMING_SNAKE_CASE_      		=     self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     config_and_inputs
       SCREAMING_SNAKE_CASE_      		=     {'pixel_values': pixel_values}
       return config, inputs_dict





@require_torch
class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE			,  _SCREAMING_SNAKE_CASE			,  unittest.TestCase   ):


 '''simple docstring'''







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

 lowercase_							       =       False
 lowercase_							       =       False
 lowercase_							       =       False
 lowercase_							       =       False



 def  lowerCAmelCase_    (				self    :						List[str]		):
       SCREAMING_SNAKE_CASE_      		=     MobileNetVaModelTester(self		)
       SCREAMING_SNAKE_CASE_      		=     MobileNetVaConfigTester(self							,							config_class=_lowerCAmelCase							,							has_text_modality=_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						List[Any]		):
       self.config_tester.run_common_tests()



 @unittest.skip(reason='MobileNetV2 does not use inputs_embeds'		)
 def  lowerCAmelCase_    (				self    :						Any		):
       pass



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



 @unittest.skip(reason='MobileNetV2 does not output attentions'		)
 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       pass



 def  lowerCAmelCase_    (				self    :						str		):
       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE_      		=     ['pixel_values']
             self.assertListEqual(arg_names[:1]							,							_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						List[Any]		):
       SCREAMING_SNAKE_CASE_      		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						int		):
       def check_hidden_states_output(_lowerCAmelCase    :						List[str]							,							_lowerCAmelCase    :						Union[str, Any]							,							_lowerCAmelCase    :						Tuple		):
             SCREAMING_SNAKE_CASE_      		=     model_class(_lowerCAmelCase		)
             model.to(_lowerCAmelCase		)
             model.eval()

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

             SCREAMING_SNAKE_CASE_      		=     outputs.hidden_states

             SCREAMING_SNAKE_CASE_      		=     16
             self.assertEqual(len(_lowerCAmelCase		)							,							_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     self.model_tester.prepare_config_and_inputs_for_common()

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

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

             check_hidden_states_output(_lowerCAmelCase							,							_lowerCAmelCase							,							_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						int		):
       SCREAMING_SNAKE_CASE_      		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						List[Any]		):
       SCREAMING_SNAKE_CASE_      		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCAmelCase		)




 @slow
 def  lowerCAmelCase_    (				self    :						Any		):
       for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE_      		=     MobileNetVaModel.from_pretrained(_lowerCAmelCase		)
             self.assertIsNotNone(_lowerCAmelCase		)


def    UpperCAmelCase_				( )   ->					Dict:
      SCREAMING_SNAKE_CASE_      		=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
      return image





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


 '''simple docstring'''







 @cached_property
 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       return (
           MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224'		) if is_vision_available() else None
       )



 @slow
 def  lowerCAmelCase_    (				self    :						List[str]		):
       SCREAMING_SNAKE_CASE_      		=     MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224'		).to(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     self.default_image_processor
       SCREAMING_SNAKE_CASE_      		=     prepare_img()
       SCREAMING_SNAKE_CASE_      		=     image_processor(images=_lowerCAmelCase							,							return_tensors='pt'		).to(_lowerCAmelCase		)

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

       # verify the logits
       SCREAMING_SNAKE_CASE_      		=     torch.Size((1, 1_001)		)
       self.assertEqual(outputs.logits.shape							,							_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     torch.tensor([0.2445, -1.1993, 0.1905]		).to(_lowerCAmelCase		)

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




 @slow
 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       SCREAMING_SNAKE_CASE_      		=     MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'		)
       SCREAMING_SNAKE_CASE_      		=     model.to(_lowerCAmelCase		)

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

       SCREAMING_SNAKE_CASE_      		=     prepare_img()
       SCREAMING_SNAKE_CASE_      		=     image_processor(images=_lowerCAmelCase							,							return_tensors='pt'		).to(_lowerCAmelCase		)

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE_      		=     model(**_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     outputs.logits

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

       SCREAMING_SNAKE_CASE_      		=     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=_lowerCAmelCase							,							)

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





def    UpperCAmelCase_				( )   ->					list[list[int]]:
      return [list(range(10_00 - i     ,     -10_00 - i     ,     -1				)				) for i in range(10_00				)]


lowerCamelCase__					:  List[Any]      							=				generate_large_matrix()
lowerCamelCase__					:  List[Any]      							=				(
    [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
    [[3, 2], [1, 0]],
    [[7, 7, 6]],
    [[7, 7, 6], [-1, -2, -3]],
    grid,
)

def    UpperCAmelCase_				( __UpperCAmelCase		:      list[list[int]]				)   ->					None:
      assert all(row == sorted(__UpperCAmelCase     ,     reverse=__UpperCAmelCase				) for row in grid				)
      assert all(list(__UpperCAmelCase				) == sorted(__UpperCAmelCase     ,     reverse=__UpperCAmelCase				) for col in zip(*__UpperCAmelCase				)				)

def    UpperCAmelCase_				( __UpperCAmelCase		:      list[int]				)   ->					int:
      SCREAMING_SNAKE_CASE_      		=     0
      SCREAMING_SNAKE_CASE_      		=     len(__UpperCAmelCase				) - 1

      # Edge cases such as no values or all numbers are negative.
      if not array or array[0] < 0:
            return 0

      while right + 1 > left:
            SCREAMING_SNAKE_CASE_      		=     (left + right) // 2
            SCREAMING_SNAKE_CASE_      		=     array[mid]

            # Num must be negative and the index must be greater than or equal to 0.
            if num < 0 and array[mid - 1] >= 0:
                  return mid

            if num >= 0:
                  SCREAMING_SNAKE_CASE_      		=     mid + 1
            else:
                  SCREAMING_SNAKE_CASE_      		=     mid - 1
    # No negative numbers so return the last index of the array + 1 which is the length.
      return len(__UpperCAmelCase				)

def    UpperCAmelCase_				( __UpperCAmelCase		:      list[list[int]]				)   ->					int:
      SCREAMING_SNAKE_CASE_      		=     0
      SCREAMING_SNAKE_CASE_      		=     len(grid[0]				)

      for i in range(len(__UpperCAmelCase				)				):
            SCREAMING_SNAKE_CASE_      		=     find_negative_index(grid[i][:bound]				)
            total += bound
      return (len(__UpperCAmelCase				) * len(grid[0]				)) - total

def    UpperCAmelCase_				( __UpperCAmelCase		:      list[list[int]]				)   ->					int:
      return len([number for row in grid for number in row if number < 0]				)

def    UpperCAmelCase_				( __UpperCAmelCase		:      list[list[int]]				)   ->					int:
      SCREAMING_SNAKE_CASE_      		=     0
      for row in grid:
            for i, number in enumerate(__UpperCAmelCase				):
                  if number < 0:
                        total += len(__UpperCAmelCase				) - i
                        break
      return total

def    UpperCAmelCase_				( )   ->					None:
      from timeit import timeit

      print('Running benchmarks'				)
      SCREAMING_SNAKE_CASE_      		=     (
          'from __main__ import count_negatives_binary_search, '
          'count_negatives_brute_force, count_negatives_brute_force_with_break, grid'
      )
      for func in (
          "count_negatives_binary_search",  # took 0.7727 seconds
          "count_negatives_brute_force_with_break",  # took 4.6505 seconds
          "count_negatives_brute_force",  # took 12.8160 seconds
      ):
            SCREAMING_SNAKE_CASE_      		=     timeit(f"{func}(grid=grid)"     ,     setup=__UpperCAmelCase     ,     number=5_00				)
            print(f"{func}() took {time:0.4f} seconds"				)


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   benchmark()