



'''simple docstring'''




import argparse
import os
import re

import packaging.version


lowerCamelCase				:Tuple							       =   '''examples/'''
lowerCamelCase				:Any							       =   {
    '''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'''),
}
lowerCamelCase				:Tuple							       =   {
    '''init''': '''src/transformers/__init__.py''',
    '''setup''': '''setup.py''',
}
lowerCamelCase				:Any							       =   '''README.md'''



def       a     (					lowerCamelCase__		, lowerCamelCase__		, lowerCamelCase__       ):
			'''simple docstring'''





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



def       a     (					lowerCamelCase__       ):
			'''simple docstring'''





			for folder, directories, fnames in os.walk(_lowerCamelCase       ):
						# 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(_lowerCamelCase		, _lowerCamelCase       )		, _lowerCamelCase		, pattern="""examples"""       )



def       a     (					lowerCamelCase__		, lowerCamelCase__=False       ):
			'''simple docstring'''





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



def       a     (					):
			'''simple docstring'''





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

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

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

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



def       a     (					):
			'''simple docstring'''





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



def       a     (					lowerCamelCase__=False       ):
			'''simple docstring'''





			A_      :		Union[str, Any]      =	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:
						A_      :		str      =	default_version.base_version
			elif patch:
						A_      :		List[str]      =	f'{default_version.major}.{default_version.minor}.{default_version.micro + 1}'
			else:
						A_      :		Optional[Any]      =	f'{default_version.major}.{default_version.minor + 1}.0'

			# Now let's ask nicely if that's the right one.
			A_      :		Union[str, Any]      =	input(f'Which version are you releasing? [{default_version}]'       )
			if len(_lowerCamelCase       ) == 0:
						A_      :		List[str]      =	default_version

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



def       a     (					):
			'''simple docstring'''





			A_      :		int      =	get_version()
			A_      :		Tuple      =	f'{current_version.major}.{current_version.minor + 1}.0.dev0'
			A_      :		List[Any]      =	current_version.base_version

			# Check with the user we got that right.
			A_      :		Optional[Any]      =	input(f'Which version are we developing now? [{dev_version}]'       )
			if len(_lowerCamelCase       ) == 0:
						A_      :		List[Any]      =	dev_version

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


if __name__ == "__main__":
						lowerCamelCase				:List[str]							       =   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.''')
						lowerCamelCase				:List[str]							       =   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()







"""simple docstring"""





import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 torch import nn

  from transformers import RegNetForImageClassification, RegNetModel
  from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class 	a		:






    def __init__(			self	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				str			,		__SCREAMING_SNAKE_CASE	:				List[str]=3			,		__SCREAMING_SNAKE_CASE	:				Optional[int]=32			,		__SCREAMING_SNAKE_CASE	:				int=3			,		__SCREAMING_SNAKE_CASE	:				str=10			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]=[10, 20, 30, 40]			,		__SCREAMING_SNAKE_CASE	:				List[Any]=[1, 1, 2, 1]			,		__SCREAMING_SNAKE_CASE	:				List[str]=True			,		__SCREAMING_SNAKE_CASE	:				Tuple=True			,		__SCREAMING_SNAKE_CASE	:				Optional[int]="relu"			,		__SCREAMING_SNAKE_CASE	:				Tuple=3			,		__SCREAMING_SNAKE_CASE	:				Dict=None			,		)	->						Optional[int]:
      lowerCamelCase_       	=		parent
      lowerCamelCase_       	=		batch_size
      lowerCamelCase_       	=		image_size
      lowerCamelCase_       	=		num_channels
      lowerCamelCase_       	=		embeddings_size
      lowerCamelCase_       	=		hidden_sizes
      lowerCamelCase_       	=		depths
      lowerCamelCase_       	=		is_training
      lowerCamelCase_       	=		use_labels
      lowerCamelCase_       	=		hidden_act
      lowerCamelCase_       	=		num_labels
      lowerCamelCase_       	=		scope
      lowerCamelCase_       	=		len(__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				List[Any]   )	->						Dict:
      lowerCamelCase_       	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

      lowerCamelCase_       	=		self.get_config()

      return config, pixel_values, labels






    def   UpperCamelCase			(			self	:				List[str]   )	->						str:
      return RegNetConfig(
          num_channels=self.num_channels			,		embeddings_size=self.embeddings_size			,		hidden_sizes=self.hidden_sizes			,		depths=self.depths			,		hidden_act=self.hidden_act			,		num_labels=self.num_labels			,		)






    def   UpperCamelCase			(			self	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				int   )	->						List[Any]:
      lowerCamelCase_       	=		RegNetModel(config=__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE   )
      # expected last hidden states: B, C, H // 32, W // 32
      self.parent.assertEqual(
          result.last_hidden_state.shape			,		(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,		)






    def   UpperCamelCase			(			self	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]   )	->						Union[str, Any]:
      lowerCamelCase_       	=		self.num_labels
      lowerCamelCase_       	=		RegNetForImageClassification(__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE			,		labels=__SCREAMING_SNAKE_CASE   )
      self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_labels)   )






    def   UpperCamelCase			(			self	:				Optional[Any]   )	->						str:
      lowerCamelCase_       	=		self.prepare_config_and_inputs()
      lowerCamelCase_	,      lowerCamelCase_	,      lowerCamelCase_       	=		config_and_inputs
      lowerCamelCase_       	=		{'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 	a		(   __snake_case    , __snake_case    , unittest.TestCase						):
    SCREAMING_SNAKE_CASE		:	int		=					(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE		:	int		=					(
        {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
        if is_torch_available()
        else {}
    )

    SCREAMING_SNAKE_CASE		:	int		=					False
    SCREAMING_SNAKE_CASE		:	Optional[int]		=					False
    SCREAMING_SNAKE_CASE		:	Optional[int]		=					False
    SCREAMING_SNAKE_CASE		:	int		=					False






    def   UpperCamelCase			(			self	:				Optional[int]   )	->						List[Any]:
      lowerCamelCase_       	=		RegNetModelTester(self   )
      lowerCamelCase_       	=		ConfigTester(self			,		config_class=__SCREAMING_SNAKE_CASE			,		has_text_modality=__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Dict   )	->						Any:
      self.create_and_test_config_common_properties()
      self.config_tester.create_and_test_config_to_json_string()
      self.config_tester.create_and_test_config_to_json_file()
      self.config_tester.create_and_test_config_from_and_save_pretrained()
      self.config_tester.create_and_test_config_with_num_labels()
      self.config_tester.check_config_can_be_init_without_params()
      self.config_tester.check_config_arguments_init()






    def   UpperCamelCase			(			self	:				Any   )	->						Optional[Any]:
      return






    @unittest.skip(reason='RegNet does not use inputs_embeds'   )
    def   UpperCamelCase			(			self	:				List[str]   )	->						Union[str, Any]:
      pass






    @unittest.skip(reason='RegNet does not support input and output embeddings'   )
    def   UpperCamelCase			(			self	:				Any   )	->						Dict:
      pass






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Dict:
      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCamelCase_       	=		['pixel_values']
        self.assertListEqual(arg_names[:1]			,		__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Tuple   )	->						List[str]:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Tuple   )	->						Dict:
      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCamelCase_       	=		model_class(config=__SCREAMING_SNAKE_CASE   )
        for name, module in model.named_modules():
          if isinstance(__SCREAMING_SNAKE_CASE			,		(nn.BatchNormad, nn.GroupNorm)   ):
            self.assertTrue(
                torch.all(module.weight == 1   )			,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''			,		)
            self.assertTrue(
                torch.all(module.bias == 0   )			,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''			,		)






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Optional[Any]:
      def check_hidden_states_output(__SCREAMING_SNAKE_CASE	:				Dict			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]   ):
        lowerCamelCase_       	=		model_class(__SCREAMING_SNAKE_CASE   )
        model.to(__SCREAMING_SNAKE_CASE   )
        model.eval()

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

        lowerCamelCase_       	=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        lowerCamelCase_       	=		self.model_tester.num_stages
        self.assertEqual(len(__SCREAMING_SNAKE_CASE   )			,		expected_num_stages + 1   )

        # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
        self.assertListEqual(
            list(hidden_states[0].shape[-2:]   )			,		[self.model_tester.image_size // 2, self.model_tester.image_size // 2]			,		)

      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()
      lowerCamelCase_       	=		['basic', 'bottleneck']
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          lowerCamelCase_       	=		layer_type
          lowerCamelCase_       	=		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_       	=		True

          check_hidden_states_output(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				List[Any]   )	->						Tuple:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE   )






    @slow
    def   UpperCamelCase			(			self	:				int   )	->						Union[str, Any]:
      for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase_       	=		RegNetModel.from_pretrained(__SCREAMING_SNAKE_CASE   )
        self.assertIsNotNone(__SCREAMING_SNAKE_CASE   )







def 	lowerCamelCase__			(				) ->							Optional[Any]:
  lowerCamelCase_       	=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
  return image






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






    @cached_property
    def   UpperCamelCase			(			self	:				Optional[int]   )	->						Optional[int]:
      return (
          AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
          if is_vision_available()
          else None
      )






    @slow
    def   UpperCamelCase			(			self	:				Optional[int]   )	->						Dict:
      lowerCamelCase_       	=		RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.default_image_processor
      lowerCamelCase_       	=		prepare_img()
      lowerCamelCase_       	=		image_processor(images=__SCREAMING_SNAKE_CASE			,		return_tensors='pt'   ).to(__SCREAMING_SNAKE_CASE   )

      # forward pass
      with torch.no_grad():
        lowerCamelCase_       	=		model(**__SCREAMING_SNAKE_CASE   )

      # verify the logits
      lowerCamelCase_       	=		torch.Size((1, 1000)   )
      self.assertEqual(outputs.logits.shape			,		__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		torch.tensor([-0.4_180, -1.5_051, -3.4_836]   ).to(__SCREAMING_SNAKE_CASE   )

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




