


import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
 import torch

 from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin






class 	__lowercase					:





      def __init__(		self    :       Union[str, Any]       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       Any=None       ,							__lowerCamelCase    :       Union[str, Any]=None       ,							__lowerCamelCase    :       int=None       ,							__lowerCamelCase    :       int="resnet50"       ,							__lowerCamelCase    :       str=3       ,							__lowerCamelCase    :       int=3_2       ,							__lowerCamelCase    :       Tuple=3       ,							__lowerCamelCase    :       List[Any]=True       ,							__lowerCamelCase    :       Union[str, Any]=True       ,							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  parent
         UpperCAmelCase      					=  out_indices if out_indices is not None else [4]
         UpperCAmelCase      					=  stage_names
         UpperCAmelCase      					=  out_features
         UpperCAmelCase      					=  backbone
         UpperCAmelCase      					=  batch_size
         UpperCAmelCase      					=  image_size
         UpperCAmelCase      					=  num_channels
         UpperCAmelCase      					=  use_pretrained_backbone
         UpperCAmelCase      					=  is_training





      def 							_lowercase					(		self    :       Tuple							)     -> List[str]:






         """simple docstring"""







         UpperCAmelCase      					=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)
         UpperCAmelCase      					=  self.get_config()

         return config, pixel_values





      def 							_lowercase					(		self    :       int							)     -> Optional[Any]:






         """simple docstring"""







         return TimmBackboneConfig(
             image_size=self.image_size       ,							num_channels=self.num_channels       ,							out_features=self.out_features       ,							out_indices=self.out_indices       ,							stage_names=self.stage_names       ,							use_pretrained_backbone=self.use_pretrained_backbone       ,							backbone=self.backbone       ,							)





      def 							_lowercase					(		self    :       str       ,							__lowerCamelCase    :       Union[str, Any]       ,							__lowerCamelCase    :       Tuple							)     -> Dict:






         """simple docstring"""







         UpperCAmelCase      					=  TimmBackbone(config=__lowerCamelCase							)
         model.to(__lowerCamelCase							)
         model.eval()
         with torch.no_grad():
            UpperCAmelCase      					=  model(__lowerCamelCase							)
         self.parent.assertEqual(
             result.feature_map[-1].shape       ,							(self.batch_size, model.channels[-1], 1_4, 1_4)       ,							)





      def 							_lowercase					(		self    :       int							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  self.prepare_config_and_inputs()
         UpperCAmelCase					,	UpperCAmelCase      					=  config_and_inputs
         UpperCAmelCase      					=  {"""pixel_values""": pixel_values}
         return config, inputs_dict






@require_torch
@require_timm
class 	__lowercase					(	__snake_case			,       __snake_case			,       __snake_case			,       unittest.TestCase	):
      UpperCamelCase										=							(TimmBackbone,) if is_torch_available() else ()
      UpperCamelCase										=							{'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False





      def 							_lowercase					(		self    :       Tuple							)     -> Union[str, Any]:






         """simple docstring"""







         UpperCAmelCase      					=  TimmBackboneModelTester(self							)
         UpperCAmelCase      					=  ConfigTester(self       ,							config_class=__lowerCamelCase       ,							has_text_modality=__lowerCamelCase							)





      def 							_lowercase					(		self    :       Optional[Any]							)     -> int:






         """simple docstring"""







         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 							_lowercase					(		self    :       Dict							)     -> str:






         """simple docstring"""







         UpperCAmelCase      					=  """resnet18"""
         UpperCAmelCase      					=  """microsoft/resnet-18"""

         UpperCAmelCase      					=  AutoBackbone.from_pretrained(__lowerCamelCase       ,							use_timm_backbone=__lowerCamelCase							)
         UpperCAmelCase      					=  AutoBackbone.from_pretrained(__lowerCamelCase							)

         self.assertEqual(len(timm_model.out_features							)       ,							len(transformers_model.out_features							)							)
         self.assertEqual(len(timm_model.stage_names							)       ,							len(transformers_model.stage_names							)							)
         self.assertEqual(timm_model.channels       ,							transformers_model.channels							)
         # Out indices are set to the last layer by default. For timm models, we don't know
         # the number of layers in advance, so we set it to (-1,), whereas for transformers
         # models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
         self.assertEqual(timm_model.out_indices       ,							(-1,)							)
         self.assertEqual(transformers_model.out_indices       ,							[len(timm_model.stage_names							) - 1]							)

         UpperCAmelCase      					=  AutoBackbone.from_pretrained(__lowerCamelCase       ,							use_timm_backbone=__lowerCamelCase       ,							out_indices=[1, 2, 3]							)
         UpperCAmelCase      					=  AutoBackbone.from_pretrained(__lowerCamelCase       ,							out_indices=[1, 2, 3]							)

         self.assertEqual(timm_model.out_indices       ,							transformers_model.out_indices							)
         self.assertEqual(len(timm_model.out_features							)       ,							len(transformers_model.out_features							)							)
         self.assertEqual(timm_model.channels       ,							transformers_model.channels							)





      @unittest.skip("""TimmBackbone doesn't support feed forward chunking"""							)
      def 							_lowercase					(		self    :       int							)     -> Optional[Any]:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute"""							)
      def 							_lowercase					(		self    :       Dict							)     -> Union[str, Any]:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone initialization is managed on the timm side"""							)
      def 							_lowercase					(		self    :       Dict							)     -> Dict:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone models doesn't have inputs_embeds"""							)
      def 							_lowercase					(		self    :       List[Any]							)     -> Tuple:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone models doesn't have inputs_embeds"""							)
      def 							_lowercase					(		self    :       List[str]							)     -> Tuple:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint"""							)
      def 							_lowercase					(		self    :       str							)     -> Optional[int]:






         """simple docstring"""







         pass





      @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""							)
      def 							_lowercase					(		self    :       Union[str, Any]							)     -> Union[str, Any]:






         """simple docstring"""







         pass





      @unittest.skip("""model weights aren't tied in TimmBackbone."""							)
      def 							_lowercase					(		self    :       str							)     -> Dict:






         """simple docstring"""







         pass





      @unittest.skip("""model weights aren't tied in TimmBackbone."""							)
      def 							_lowercase					(		self    :       Optional[Any]							)     -> Optional[int]:






         """simple docstring"""







         pass





      @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""							)
      def 							_lowercase					(		self    :       Tuple							)     -> Optional[Any]:






         """simple docstring"""







         pass





      @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone"""							)
      def 							_lowercase					(		self    :       str							)     -> List[str]:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration."""							)
      def 							_lowercase					(		self    :       Dict							)     -> Tuple:






         """simple docstring"""







         pass





      @unittest.skip("""TimmBackbone doesn't support output_attentions."""							)
      def 							_lowercase					(		self    :       Union[str, Any]							)     -> Union[str, Any]:






         """simple docstring"""







         pass





      @unittest.skip("""Safetensors is not supported by timm."""							)
      def 							_lowercase					(		self    :       Union[str, Any]							)     -> Optional[int]:






         """simple docstring"""







         pass





      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""							)
      def 							_lowercase					(		self    :       Union[str, Any]							)     -> Tuple:






         """simple docstring"""







         pass





      def 							_lowercase					(		self    :       List[str]							)     -> Union[str, Any]:






         """simple docstring"""







         UpperCAmelCase					,	UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()

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

            UpperCAmelCase      					=  ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]       ,							__lowerCamelCase							)





      def 							_lowercase					(		self    :       int							)     -> Dict:






         """simple docstring"""







         UpperCAmelCase					,	UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase      					=  True
         UpperCAmelCase      					=  self.has_attentions

         # no need to test all models as different heads yield the same functionality
         UpperCAmelCase      					=  self.all_model_classes[0]
         UpperCAmelCase      					=  model_class(__lowerCamelCase							)
         model.to(__lowerCamelCase							)

         UpperCAmelCase      					=  self._prepare_for_class(__lowerCamelCase       ,							__lowerCamelCase							)
         UpperCAmelCase      					=  model(**__lowerCamelCase							)
         UpperCAmelCase      					=  outputs[0][-1]

         # Encoder-/Decoder-only models
         UpperCAmelCase      					=  outputs.hidden_states[0]
         hidden_states.retain_grad()

         if self.has_attentions:
            UpperCAmelCase      					=  outputs.attentions[0]
            attentions.retain_grad()

         output.flatten()[0].backward(retain_graph=__lowerCamelCase							)

         self.assertIsNotNone(hidden_states.grad							)

         if self.has_attentions:
            self.assertIsNotNone(attentions.grad							)





      def 							_lowercase					(		self    :       List[Any]							)     -> Optional[int]:






         """simple docstring"""







         UpperCAmelCase					,	UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            UpperCAmelCase      					=  model(**__lowerCamelCase							)

            self.assertEqual(len(result.feature_maps							)       ,							len(config.out_indices							)							)
            self.assertEqual(len(model.channels							)       ,							len(config.out_indices							)							)

            # Check output of last stage is taken if out_features=None, out_indices=None
            UpperCAmelCase      					=  copy.deepcopy(__lowerCamelCase							)
            UpperCAmelCase      					=  None
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            UpperCAmelCase      					=  model(**__lowerCamelCase							)

            self.assertEqual(len(result.feature_maps							)       ,							1							)
            self.assertEqual(len(model.channels							)       ,							1							)

            # Check backbone can be initialized with fresh weights
            UpperCAmelCase      					=  copy.deepcopy(__lowerCamelCase							)
            UpperCAmelCase      					=  False
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            UpperCAmelCase      					=  model(**__lowerCamelCase							)







import argparse
import os
import re

import packaging.version


__a	 =      """examples/"""
__a	 =      {
    """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"""),
}
__a	 =      {
    """init""": """src/diffusers/__init__.py""",
    """setup""": """setup.py""",
}
__a	 =      """README.md"""
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Optional[Any]:
   with open(lowerCAmelCase_	,    """r"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      UpperCAmelCase      					=  f.read()
   UpperCAmelCase					,	UpperCAmelCase      					=  REPLACE_PATTERNS[pattern]
   UpperCAmelCase      					=  replace.replace("""VERSION"""	,    lowerCAmelCase_ )
   UpperCAmelCase      					=  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_	,    lowerCAmelCase_=False )    ->Optional[int]:
   for pattern, fname in REPLACE_FILES.items():
      update_version_in_file(lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )
   if not patch:
      update_version_in_examples(lowerCAmelCase_ )
def 	_UpperCamelCase					(    )    ->List[str]:
   UpperCAmelCase      					=  """🤗 Transformers currently provides the following architectures"""
   UpperCAmelCase      					=  """1. Want to contribute a new model?"""
   with open(lowerCAmelCase_	,    """r"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      UpperCAmelCase      					=  f.readlines()

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

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

   with open(lowerCAmelCase_	,    """w"""	,    encoding="""utf-8"""	,    newline="""\n""" ) as f:
      f.writelines(lowerCAmelCase_ )
def 	_UpperCamelCase					(    )    ->List[str]:
   with open(REPLACE_FILES["""init"""]	,    """r""" ) as f:
      UpperCAmelCase      					=  f.read()
   UpperCAmelCase      					=  REPLACE_PATTERNS["""init"""][0].search(lowerCAmelCase_ ).groups()[0]
   return packaging.version.parse(lowerCAmelCase_ )
def 	_UpperCamelCase					(    lowerCAmelCase_=False )    ->int:
   UpperCAmelCase      					=  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:
      UpperCAmelCase      					=  default_version.base_version
   elif patch:
      UpperCAmelCase      					=  F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
   else:
      UpperCAmelCase      					=  F"""{default_version.major}.{default_version.minor + 1}.0"""

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

   print(F"""Updating version to {version}.""" )
   global_version_update(lowerCAmelCase_	,    patch=lowerCAmelCase_ )
def 	_UpperCamelCase					(    )    ->int:
   UpperCAmelCase      					=  get_version()
   UpperCAmelCase      					=  F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
   UpperCAmelCase      					=  current_version.base_version

   # Check with the user we got that right.
   UpperCAmelCase      					=  input(F"""Which version are we developing now? [{dev_version}]""" )
   if len(lowerCAmelCase_ ) == 0:
      UpperCAmelCase      					=  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__":
 __a	 =      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.""")
 __a	 =      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()



