





'''simple docstring'''

import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
  from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class        UpperCAmelCase     :
 def __init__(    self				:int						,	lowercase_				:Dict						,	lowercase_				:Optional[int]=13						,	lowercase_				:List[str]=32						,	lowercase_				:Dict=3						,	lowercase_				:Any=4						,	lowercase_				:List[Any]=[10, 20, 30, 40]						,	lowercase_				:Union[str, Any]=[2, 2, 3, 2]						,	lowercase_				:Optional[int]=True						,	lowercase_				:Any=True						,	lowercase_				:Union[str, Any]=37						,	lowercase_				:int="gelu"						,	lowercase_				:List[str]=10						,	lowercase_				:Any=0.0_2						,	lowercase_				:Union[str, Any]=["stage2", "stage3", "stage4"]						,	lowercase_				:Union[str, Any]=[2, 3, 4]						,	lowercase_				:Optional[Any]=None						,	)->							Any:
     A__    =      parent
     A__    =      batch_size
     A__    =      image_size
     A__    =      num_channels
     A__    =      num_stages
     A__    =      hidden_sizes
     A__    =      depths
     A__    =      is_training
     A__    =      use_labels
     A__    =      intermediate_size
     A__    =      hidden_act
     A__    =      num_labels
     A__    =      initializer_range
     A__    =      out_features
     A__    =      out_indices
     A__    =      scope
 def 					UpperCAmelCase_							(    self				:str							)->							Union[str, Any]:
     A__    =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

     A__    =      self.get_config()

     return config, pixel_values, labels
 def 					UpperCAmelCase_							(    self				:int							)->							List[str]:
     return ConvNextVaConfig(
         num_channels=self.num_channels						,	hidden_sizes=self.hidden_sizes						,	depths=self.depths						,	num_stages=self.num_stages						,	hidden_act=self.hidden_act						,	is_decoder=_A						,	initializer_range=self.initializer_range						,	out_features=self.out_features						,	out_indices=self.out_indices						,	num_labels=self.num_labels						,	)
 def 					UpperCAmelCase_							(    self				:str						,	lowercase_				:Optional[Any]						,	lowercase_				:int						,	lowercase_				:str							)->							Optional[Any]:
     A__    =      ConvNextVaModel(config=_A							)
     model.to(_A							)
     model.eval()
     A__    =      model(_A							)
     # 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				:Optional[Any]						,	lowercase_				:Optional[int]						,	lowercase_				:List[Any]						,	lowercase_				:int							)->							int:
     A__    =      ConvNextVaForImageClassification(_A							)
     model.to(_A							)
     model.eval()
     A__    =      model(_A						,	labels=_A							)
     self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.num_labels)							)
 def 					UpperCAmelCase_							(    self				:Optional[int]						,	lowercase_				:Any						,	lowercase_				:Dict						,	lowercase_				:Optional[int]							)->							List[Any]:
     A__    =      ConvNextVaBackbone(config=_A							)
     model.to(_A							)
     model.eval()
     A__    =      model(_A							)

     # verify hidden states
     self.parent.assertEqual(len(result.feature_maps							)						,	len(config.out_features							)							)
     self.parent.assertListEqual(list(result.feature_maps[0].shape							)						,	[self.batch_size, self.hidden_sizes[1], 4, 4]							)

     # verify channels
     self.parent.assertEqual(len(model.channels							)						,	len(config.out_features							)							)
     self.parent.assertListEqual(model.channels						,	config.hidden_sizes[1:]							)

     # verify backbone works with out_features=None
     A__    =      None
     A__    =      ConvNextVaBackbone(config=_A							)
     model.to(_A							)
     model.eval()
     A__    =      model(_A							)

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps							)						,	1							)
     self.parent.assertListEqual(list(result.feature_maps[0].shape							)						,	[self.batch_size, self.hidden_sizes[-1], 1, 1]							)

     # verify channels
     self.parent.assertEqual(len(model.channels							)						,	1							)
     self.parent.assertListEqual(model.channels						,	[config.hidden_sizes[-1]]							)
 def 					UpperCAmelCase_							(    self				:str							)->							Optional[int]:
     A__    =      self.prepare_config_and_inputs()
     A__,     A__,     A__    =      config_and_inputs
     A__    =      {"pixel_values": pixel_values}
     return config, inputs_dict



 def 					UpperCAmelCase_							(    self				:Any							)->							int:
     A__    =      self.prepare_config_and_inputs()
     A__,     A__,     A__    =      config_and_inputs
     A__    =      {"pixel_values": pixel_values, "labels": labels}
     return config, inputs_dict






@require_torch
class        UpperCAmelCase     (	snake_case__      ,	snake_case__      ,	unittest.TestCase    ):
 __lowercase       		=    (
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 __lowercase       		=    (
     {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 __lowercase       		=    False
 __lowercase       		=    False
 __lowercase       		=    False
 __lowercase       		=    False
 __lowercase       		=    False
 def 					UpperCAmelCase_							(    self				:Any							)->							Tuple:
     A__    =      ConvNextVaModelTester(self							)
     A__    =      ConfigTester(self						,	config_class=_A						,	has_text_modality=_A						,	hidden_size=37							)
 def 					UpperCAmelCase_							(    self				:str							)->							Union[str, 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				:Tuple							)->							Optional[Any]:
     return
 @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"							)
 def 					UpperCAmelCase_							(    self				:List[str]							)->							Tuple:
     pass
 @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"							)
 def 					UpperCAmelCase_							(    self				:Any							)->							Optional[int]:
     pass
 @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"							)
 def 					UpperCAmelCase_							(    self				:Union[str, Any]							)->							int:
     pass
 def 					UpperCAmelCase_							(    self				:List[str]							)->							List[str]:



     if not self.model_tester.is_training:
         return

     for model_class in self.all_model_classes:
         A__,     A__    =      self.model_tester.prepare_config_and_inputs_with_labels()
         A__    =      True

         if model_class.__name__ in [
             *get_values(_A							),
             *get_values(_A							),
         ]:
             continue

         A__    =      model_class(_A							)
         model.to(_A							)
         model.train()
         A__    =      self._prepare_for_class(_A						,	_A						,	return_labels=_A							)
         A__    =      model(**_A							).loss
         loss.backward()
 def 					UpperCAmelCase_							(    self				:Tuple							)->							int:



     if not self.model_tester.is_training:
         return

     for model_class in self.all_model_classes:
         A__,     A__    =      self.model_tester.prepare_config_and_inputs_with_labels()
         A__    =      False
         A__    =      True

         if (
             model_class.__name__
             in [*get_values(_A							), *get_values(_A							)]
             or not model_class.supports_gradient_checkpointing
         ):
             continue

         A__    =      model_class(_A							)
         model.to(_A							)
         model.gradient_checkpointing_enable()
         model.train()
         A__    =      self._prepare_for_class(_A						,	_A						,	return_labels=_A							)
         A__    =      model(**_A							).loss
         loss.backward()
 def 					UpperCAmelCase_							(    self				:Any							)->							List[Any]:
     A__,     A__    =      self.model_tester.prepare_config_and_inputs_for_common()

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

         A__    =      ["pixel_values"]
         self.assertListEqual(arg_names[:1]						,	_A							)
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							List[Any]:
     A__    =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_A							)
 def 					UpperCAmelCase_							(    self				:List[str]							)->							Optional[int]:



     def check_hidden_states_output(lowercase_				:str						,	lowercase_				:int						,	lowercase_				:Union[str, Any]							):
         A__    =      model_class(_A							)
         model.to(_A							)
         model.eval()

         with torch.no_grad():
             A__    =      model(**self._prepare_for_class(_A						,	_A							)							)

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

         A__    =      self.model_tester.num_stages
         self.assertEqual(len(_A							)						,	expected_num_stages + 1							)

         # ConvNextV2'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 // 4, self.model_tester.image_size // 4]						,	)

     A__,     A__    =      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         A__    =      True
         check_hidden_states_output(_A						,	_A						,	_A							)

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

         check_hidden_states_output(_A						,	_A						,	_A							)
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							List[str]:
     A__    =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_A							)



 @slow
 def 					UpperCAmelCase_							(    self				:Any							)->							int:



     for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         A__    =      ConvNextVaModel.from_pretrained(_A							)
         self.assertIsNotNone(_A							)





def 						UpperCamelCase    (					):
    A__    =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
    return image






@require_torch
@require_vision
class        UpperCAmelCase     (	unittest.TestCase    ):
 @cached_property
 def 					UpperCAmelCase_							(    self				:int							)->							Any:
     return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"							) if is_vision_available() else None



 @slow
 def 					UpperCAmelCase_							(    self				:Optional[Any]							)->							Dict:
     A__    =      ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"							).to(_A							)

     A__    =      self.default_image_processor
     A__    =      prepare_img()
     A__    =      preprocessor(images=_A						,	return_tensors="pt"							).to(_A							)

     # forward pass
     with torch.no_grad():
         A__    =      model(**_A							)

     # verify the logits
     A__    =      torch.Size((1, 10_00)							)
     self.assertEqual(outputs.logits.shape						,	_A							)

     A__    =      torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]							).to(_A							)
     self.assertTrue(torch.allclose(outputs.logits[0, :3]						,	_A						,	atol=1E-4							)							)










'''simple docstring'''

import argparse
import os
import re

import packaging.version


__lowerCAmelCase							:     List[Any]		     ="examples/"
__lowerCAmelCase							:     Dict		     ={
    "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							:     List[str]		     ={
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
__lowerCAmelCase							:     str		     ="README.md"





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





def 						UpperCamelCase    (							_lowerCamelCase : int	):
    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 						UpperCamelCase    (							_lowerCamelCase : int						,	_lowerCamelCase : Union[str, Any]=False	):
    for pattern, fname in REPLACE_FILES.items():
        update_version_in_file(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)
    if not patch:
        update_version_in_examples(_lowerCamelCase	)





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

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

    A__    =      start_index
    # Update the lines in the model list.
    while not lines[index].startswith(_end_prompt	):
        if lines[index].startswith("1."	):
            A__    =      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 						UpperCamelCase    (							):
    with open(REPLACE_FILES["init"]						,	"r"	) as f:
        A__    =      f.read()
    A__    =      REPLACE_PATTERNS["init"][0].search(_lowerCamelCase	).groups()[0]
    return packaging.version.parse(_lowerCamelCase	)





def 						UpperCamelCase    (							_lowerCamelCase : Dict=False	):
    A__    =      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__    =      default_version.base_version
    elif patch:
        A__    =      F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
    else:
        A__    =      F"{default_version.major}.{default_version.minor + 1}.0"

    # Now let's ask nicely if that's the right one.
    A__    =      input(F"Which version are you releasing? [{default_version}]"	)
    if len(_lowerCamelCase	) == 0:
        A__    =      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 						UpperCamelCase    (							):
    A__    =      get_version()
    A__    =      F"{current_version.major}.{current_version.minor + 1}.0.dev0"
    A__    =      current_version.base_version

    # Check with the user we got that right.
    A__    =      input(F"Which version are we developing now? [{dev_version}]"	)
    if len(_lowerCamelCase	) == 0:
        A__    =      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							:     Union[str, Any]		     =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							:     int		     =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()



