






"""simple docstring"""


import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor






class 						snake_case  :





    def __init__(							self     : str    ,		A     : Union[str, Any]    ,		A     : Union[str, Any]=1_3    ,		A     : Union[str, Any]=3_2    ,		A     : Optional[Any]=3    ,		A     : Optional[Any]=4    ,		A     : List[Any]=[1_0, 2_0, 3_0, 4_0]    ,		A     : Dict=[2, 2, 3, 2]    ,		A     : Union[str, Any]=True    ,		A     : str=True    ,		A     : List[str]=3_7    ,		A     : Optional[int]="gelu"    ,		A     : int=1_0    ,		A     : List[Any]=0.02    ,		A     : int=["stage2", "stage3", "stage4"]    ,		A     : Optional[Any]=[2, 3, 4]    ,		A     : int=None    ,		):


      '''simple docstring'''




      a					:      int    =       parent
      a					:      str    =       batch_size
      a					:      int    =       image_size
      a					:      Union[str, Any]    =       num_channels
      a					:      Union[str, Any]    =       num_stages
      a					:      Dict    =       hidden_sizes
      a					:      Any    =       depths
      a					:      str    =       is_training
      a					:      Optional[int]    =       use_labels
      a					:      List[str]    =       intermediate_size
      a					:      int    =       hidden_act
      a					:      str    =       num_labels
      a					:      Optional[int]    =       initializer_range
      a					:      List[str]    =       out_features
      a					:      Dict    =       out_indices
      a					:      Tuple    =       scope





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




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

      a					:      Any    =       None
      if self.use_labels:
        a					:      Optional[Any]    =       ids_tensor([self.batch_size]    ,		self.num_labels      )

      a					:      Optional[int]    =       self.get_config()
      return config, pixel_values, labels





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      return ConvNextConfig(
          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     lowerCamelCase__				(							self     : Optional[int]    ,		A     : Dict    ,		A     : List[Any]    ,		A     : Tuple      ):


      '''simple docstring'''




      a					:      str    =       ConvNextModel(config=A      )
      model.to(A      )
      model.eval()
      a					:      int    =       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 // 3_2, self.image_size // 3_2)    ,		)





    def     lowerCamelCase__				(							self     : str    ,		A     : Union[str, Any]    ,		A     : Dict    ,		A     : Tuple      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       ConvNextForImageClassification(A      )
      model.to(A      )
      model.eval()
      a					:      int    =       model(A    ,		labels=A      )
      self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.num_labels)      )





    def     lowerCamelCase__				(							self     : Optional[int]    ,		A     : Optional[int]    ,		A     : int    ,		A     : Dict      ):


      '''simple docstring'''




      a					:      Optional[int]    =       ConvNextBackbone(config=A      )
      model.to(A      )
      model.eval()
      a					:      str    =       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					:      Union[str, Any]    =       None
      a					:      Optional[int]    =       ConvNextBackbone(config=A      )
      model.to(A      )
      model.eval()
      a					:      int    =       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     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      a					:      List[Any]    =       self.prepare_config_and_inputs()
      a					:      List[str]    =       config_and_inputs
      a					:      Tuple    =       {'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 						snake_case  (  UpperCAmelCase       ,			UpperCAmelCase       ,			unittest.TestCase	):
    __magic_name__   					=					(
        (
            ConvNextModel,
            ConvNextForImageClassification,
            ConvNextBackbone,
        )
        if is_torch_available()
        else ()
    )
    __magic_name__   					=					(
        {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
        if is_torch_available()
        else {}
    )

    __magic_name__   					=					True
    __magic_name__   					=					False
    __magic_name__   					=					False
    __magic_name__   					=					False
    __magic_name__   					=					False





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       ConvNextModelTester(self      )
      a					:      List[str]    =       ConfigTester(self    ,		config_class=A    ,		has_text_modality=A    ,		hidden_size=3_7      )





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      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     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      return





    @unittest.skip(reason='ConvNext does not use inputs_embeds'      )
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      pass





    @unittest.skip(reason='ConvNext does not support input and output embeddings'      )
    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      pass





    @unittest.skip(reason='ConvNext does not use feedforward chunking'      )
    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      pass





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      str    =       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a					:      List[Any]    =       model_class(A      )
        a					:      Tuple    =       inspect.signature(model.forward      )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        a					:      Dict    =       [*signature.parameters.keys()]

        a					:      int    =       ['pixel_values']
        self.assertListEqual(arg_names[:1]    ,		A      )





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      a					:      str    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A      )





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      a					:      List[str]    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*A      )





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      def check_hidden_states_output(A     : Union[str, Any]    ,		A     : List[Any]    ,		A     : Union[str, Any]      ):
        a					:      int    =       model_class(A      )
        model.to(A      )
        model.eval()

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

        a					:      int    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        a					:      Tuple    =       self.model_tester.num_stages
        self.assertEqual(len(A      )    ,		expected_num_stages + 1      )

        # ConvNext'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					:      List[str]    =       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a					:      List[str]    =       True
        check_hidden_states_output(A    ,		A    ,		A      )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        a					:      str    =       True

        check_hidden_states_output(A    ,		A    ,		A      )





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      str    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*A      )





    @slow
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a					:      Tuple    =       ConvNextModel.from_pretrained(A      )
        self.assertIsNotNone(A      )




def       snake_case  ():







  '''simple docstring'''

  a					:      List[str]    =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
  return image






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





    @cached_property
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'      ) if is_vision_available() else None





    @slow
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'      ).to(A      )

      a					:      Optional[int]    =       self.default_image_processor
      a					:      Optional[Any]    =       prepare_img()
      a					:      str    =       image_processor(images=A    ,		return_tensors='pt'      ).to(A      )

      # forward pass
      with torch.no_grad():
        a					:      Any    =       model(**A      )

      # verify the logits
      a					:      Optional[int]    =       torch.Size((1, 1_0_0_0)      )
      self.assertEqual(outputs.logits.shape    ,		A      )

      a					:      Optional[Any]    =       torch.tensor([-0.02_60, -0.47_39, 0.19_11]      ).to(A      )

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






@require_torch
class 						snake_case  (  unittest.TestCase       ,			UpperCAmelCase	):
    __magic_name__   					=					(ConvNextBackbone,) if is_torch_available() else ()
    __magic_name__   					=					ConvNextConfig

    __magic_name__   					=					False





    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       ConvNextModelTester(self      )












"""simple docstring"""


import argparse
import os
import re

import packaging.version


_UpperCamelCase    :   Optional[Any]   			=						'examples/'
_UpperCamelCase    :   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'),
}
_UpperCamelCase    :   List[str]   			=						{
    'init': 'src/diffusers/__init__.py',
    'setup': 'setup.py',
}
_UpperCamelCase    :   List[str]   			=						'README.md'




def       snake_case  (A_				:str     ,      A_				:Optional[Any]     ,      A_				:Any				):







  '''simple docstring'''

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




def       snake_case  (A_				:List[Any]				):







  '''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       snake_case  (A_				:Tuple     ,      A_				:Optional[Any]=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       snake_case  ():







  '''simple docstring'''

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

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

  a					:      Optional[Any]    =       start_index
  # Update the lines in the model list.
  while not lines[index].startswith(_end_prompt				):
    if lines[index].startswith('1.'				):
      a					:      int    =       lines[index].replace(
          'https://huggingface.co/docs/diffusers/main/model_doc'     ,      'https://huggingface.co/docs/diffusers/model_doc'     ,      )
    index += 1

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




def       snake_case  ():







  '''simple docstring'''

  with open(REPLACE_FILES['init']     ,      'r'				) as f:
    a					:      List[str]    =       f.read()
  a					:      str    =       REPLACE_PATTERNS['init'][0].search(A_				).groups()[0]
  return packaging.version.parse(A_				)




def       snake_case  (A_				:Optional[Any]=False				):







  '''simple docstring'''

  a					:      Optional[int]    =       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					:      Tuple    =       default_version.base_version
  elif patch:
    a					:      Union[str, Any]    =       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(A_				) == 0:
    a					:      int    =       default_version

  print(f'''Updating version to {version}.'''				)
  global_version_update(A_     ,      patch=A_				)




def       snake_case  ():







  '''simple docstring'''

  a					:      str    =       get_version()
  a					:      Optional[int]    =       f'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
  a					:      Optional[int]    =       current_version.base_version

  # Check with the user we got that right.
  a					:      str    =       input(f'''Which version are we developing now? [{dev_version}]'''				)
  if len(A_				) == 0:
    a					:      Union[str, 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__":
   _UpperCamelCase    :   Dict   			=						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.')
   _UpperCamelCase    :   Optional[Any]   			=						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()




