


"""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 	lowercase__				(					A_				):





   def 		UpperCamelCase_  (							self)  ->  Optional[int]:
      _lowerCamelCase	:					Dict   =		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 	lowercase__				:





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





   def 		UpperCamelCase_  (							self)  ->  Union[str, Any]:
      _lowerCamelCase	:					Any   =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

      _lowerCamelCase	:					Dict   =		self.get_config()

      return config, pixel_values, labels, pixel_labels





   def 		UpperCamelCase_  (							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 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  str:
      _lowerCamelCase	:					Tuple   =		MobileNetVaModel(config=SCREAMING_SNAKE_CASE)
      model.to(SCREAMING_SNAKE_CASE)
      model.eval()
      _lowerCamelCase	:					str   =		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 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  Tuple:
      _lowerCamelCase	:					Tuple   =		self.num_labels
      _lowerCamelCase	:					Union[str, Any]   =		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 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  int:
      _lowerCamelCase	:					Tuple   =		self.num_labels
      _lowerCamelCase	:					List[str]   =		MobileNetVaForSemanticSegmentation(SCREAMING_SNAKE_CASE)
      model.to(SCREAMING_SNAKE_CASE)
      model.eval()
      _lowerCamelCase	:					int   =		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	:					Tuple   =		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 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      _lowerCamelCase	:					Tuple   =		self.prepare_config_and_inputs()
      _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase	:					Tuple   =		config_and_inputs
      _lowerCamelCase	:					Optional[Any]   =		{"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_torch
class 	lowercase__				(					A_ ,A_ ,unittest.TestCase				):
   __UpperCAmelCase							       =					(
       (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   __UpperCAmelCase							       =					(
       {
           '''feature-extraction''': MobileNetVaModel,
           '''image-classification''': MobileNetVaForImageClassification,
           '''image-segmentation''': MobileNetVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase							       =					False
   __UpperCAmelCase							       =					False
   __UpperCAmelCase							       =					False
   __UpperCAmelCase							       =					False





   def 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      _lowerCamelCase	:					int   =		MobileNetVaModelTester(self)
      _lowerCamelCase	:					Dict   =		MobileNetVaConfigTester(self      ,   config_class=SCREAMING_SNAKE_CASE      ,   has_text_modality=SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  Dict:
      self.config_tester.run_common_tests()





   @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds""")
   def 		UpperCamelCase_  (							self)  ->  Optional[int]:
      pass





   @unittest.skip(reason="""MobileNetV2 does not support input and output embeddings""")
   def 		UpperCamelCase_  (							self)  ->  Dict:
      pass





   @unittest.skip(reason="""MobileNetV2 does not output attentions""")
   def 		UpperCamelCase_  (							self)  ->  Any:
      pass





   def 		UpperCamelCase_  (							self)  ->  List[Any]:
      _lowerCamelCase   ,    _lowerCamelCase	:					Dict   =		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         _lowerCamelCase	:					Union[str, Any]   =		model_class(SCREAMING_SNAKE_CASE)
         _lowerCamelCase	:					Tuple   =		inspect.signature(model.forward)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _lowerCamelCase	:					Optional[Any]   =		[*signature.parameters.keys()]

         _lowerCamelCase	:					Optional[Any]   =		["""pixel_values"""]
         self.assertListEqual(arg_names[:1]      ,   SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  int:
      _lowerCamelCase	:					str   =		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  List[Any]:
      def check_hidden_states_output(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE):
         _lowerCamelCase	:					List[str]   =		model_class(SCREAMING_SNAKE_CASE)
         model.to(SCREAMING_SNAKE_CASE)
         model.eval()

         with torch.no_grad():
            _lowerCamelCase	:					List[Any]   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE))

         _lowerCamelCase	:					Optional[Any]   =		outputs.hidden_states

         _lowerCamelCase	:					Tuple   =		16
         self.assertEqual(len(SCREAMING_SNAKE_CASE)      ,   SCREAMING_SNAKE_CASE)

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

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

         check_hidden_states_output(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  Tuple:
      _lowerCamelCase	:					str   =		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  Dict:
      _lowerCamelCase	:					Optional[int]   =		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE)





   @slow
   def 		UpperCamelCase_  (							self)  ->  Tuple:
      for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowerCamelCase	:					str   =		MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE)
         self.assertIsNotNone(SCREAMING_SNAKE_CASE)







def 				_snake_case      (   ):




   """simple docstring"""







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





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





   @cached_property
   def 		UpperCamelCase_  (							self)  ->  Any:
      return (
          MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v2_1.0_224""") if is_vision_available() else None
      )





   @slow
   def 		UpperCamelCase_  (							self)  ->  Dict:
      _lowerCamelCase	:					List[str]   =		MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224""").to(SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Union[str, Any]   =		self.default_image_processor
      _lowerCamelCase	:					int   =		prepare_img()
      _lowerCamelCase	:					Optional[Any]   =		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)

      # verify the logits
      _lowerCamelCase	:					Optional[int]   =		torch.Size((1, 1001))
      self.assertEqual(outputs.logits.shape      ,   SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Tuple   =		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 		UpperCamelCase_  (							self)  ->  List[str]:
      _lowerCamelCase	:					Optional[int]   =		MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""")
      _lowerCamelCase	:					str   =		model.to(SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Dict   =		MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""")

      _lowerCamelCase	:					Union[str, Any]   =		prepare_img()
      _lowerCamelCase	:					Any   =		image_processor(images=SCREAMING_SNAKE_CASE      ,   return_tensors="""pt""").to(SCREAMING_SNAKE_CASE)

      # forward pass
      with torch.no_grad():
         _lowerCamelCase	:					List[Any]   =		model(**SCREAMING_SNAKE_CASE)
      _lowerCamelCase	:					Optional[Any]   =		outputs.logits

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

      _lowerCamelCase	:					Optional[Any]   =		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))





import argparse
import os
import re

import packaging.version


SCREAMING_SNAKE_CASE__     					=			"examples/"
SCREAMING_SNAKE_CASE__     					=			{
    "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
SCREAMING_SNAKE_CASE__     					=			{
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
SCREAMING_SNAKE_CASE__     					=			"README.md"


def     lowercase	(    a     , a     , a ):



		'''simple docstring'''




		with open(a     , "r"     , encoding="utf-8"     , newline="\n" ) as f:
				SCREAMING_SNAKE_CASE_				:Dict				     =						f.read()
		SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						REPLACE_PATTERNS[pattern]
		SCREAMING_SNAKE_CASE_				:List[str]				     =						replace.replace("VERSION"     , a )
		SCREAMING_SNAKE_CASE_				:str				     =						re_pattern.sub(a     , a )
		with open(a     , "w"     , encoding="utf-8"     , newline="\n" ) as f:
				f.write(a )


def     lowercase	(    a ):



		'''simple docstring'''




		for folder, directories, fnames in os.walk(a ):
				# Removing some of the folders with non-actively maintained examples from the walk
				if "research_projects" in directories:
						directories.remove("research_projects" )
				if "legacy" in directories:
						directories.remove("legacy" )
				for fname in fnames:
						if fname.endswith(".py" ):
								update_version_in_file(os.path.join(a     , a )     , a     , pattern="examples" )


def     lowercase	(    a     , a=False ):



		'''simple docstring'''




		for pattern, fname in REPLACE_FILES.items():
				update_version_in_file(a     , a     , a )
		if not patch:
				update_version_in_examples(a )


def     lowercase	(    ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:int				     =						"🤗 Transformers currently provides the following architectures"
		SCREAMING_SNAKE_CASE_				:Any				     =						"1. Want to contribute a new model?"
		with open(a     , "r"     , encoding="utf-8"     , newline="\n" ) as f:
				SCREAMING_SNAKE_CASE_				:List[str]				     =						f.readlines()

		# Find the start of the list.
		SCREAMING_SNAKE_CASE_				:int				     =						0
		while not lines[start_index].startswith(_start_prompt ):
				start_index += 1
		start_index += 1

		SCREAMING_SNAKE_CASE_				:int				     =						start_index
		# Update the lines in the model list.
		while not lines[index].startswith(_end_prompt ):
				if lines[index].startswith("1." ):
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						lines[index].replace(
						    "https://huggingface.co/docs/transformers/main/model_doc"     , "https://huggingface.co/docs/transformers/model_doc"     , )
				index += 1

		with open(a     , "w"     , encoding="utf-8"     , newline="\n" ) as f:
				f.writelines(a )


def     lowercase	(    ):



		'''simple docstring'''




		with open(REPLACE_FILES["init"]     , "r" ) as f:
				SCREAMING_SNAKE_CASE_				:str				     =						f.read()
		SCREAMING_SNAKE_CASE_				:Optional[int]				     =						REPLACE_PATTERNS["init"][0].search(a ).groups()[0]
		return packaging.version.parse(a )


def     lowercase	(    a=False ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:str				     =						get_version()
		if patch and default_version.is_devrelease:
				raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" )
		if default_version.is_devrelease:
				SCREAMING_SNAKE_CASE_				:int				     =						default_version.base_version
		elif patch:
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
		else:
				SCREAMING_SNAKE_CASE_				:List[str]				     =						F"{default_version.major}.{default_version.minor + 1}.0"

		# Now let's ask nicely if that's the right one.
		SCREAMING_SNAKE_CASE_				:List[Any]				     =						input(F"Which version are you releasing? [{default_version}]" )
		if len(a ) == 0:
				SCREAMING_SNAKE_CASE_				:Any				     =						default_version

		print(F"Updating version to {version}." )
		global_version_update(a     , patch=a )
		if not patch:
				print("Cleaning main README, don't forget to run `make fix-copies`." )
				clean_main_ref_in_model_list()


def     lowercase	(    ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						get_version()
		SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						F"{current_version.major}.{current_version.minor + 1}.0.dev0"
		SCREAMING_SNAKE_CASE_				:str				     =						current_version.base_version

		# Check with the user we got that right.
		SCREAMING_SNAKE_CASE_				:Any				     =						input(F"Which version are we developing now? [{dev_version}]" )
		if len(a ) == 0:
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						dev_version

		print(F"Updating version to {version}." )
		global_version_update(a )
		print("Cleaning main README, don't forget to run `make fix-copies`." )
		clean_main_ref_in_model_list()


if __name__ == "__main__":
		SCREAMING_SNAKE_CASE__     					=			argparse.ArgumentParser()
		parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
		parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
		SCREAMING_SNAKE_CASE__     					=			parser.parse_args()
		if not args.post_release:
				pre_release_work(patch=args.patch)
		elif args.patch:
				print("Nothing to do after a patch :-)")
		else:
				post_release_work()






