





import argparse
import os
import re

import packaging.version


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




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       Tuple:
  with open(_SCREAMING_SNAKE_CASE		,						'r'		,						encoding='utf-8'		,						newline='\n'		) as f:
    lowercase__           =  f.read()
  lowercase__      ,   lowercase__           =  REPLACE_PATTERNS[pattern]
  lowercase__           =  replace.replace('VERSION'		,						_SCREAMING_SNAKE_CASE		)
  lowercase__           =  re_pattern.sub(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
  with open(_SCREAMING_SNAKE_CASE		,						'w'		,						encoding='utf-8'		,						newline='\n'		) as f:
    f.write(_SCREAMING_SNAKE_CASE		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       Dict:
  for folder, directories, fnames in os.walk(_SCREAMING_SNAKE_CASE		):
    # 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(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)		,						_SCREAMING_SNAKE_CASE		,						pattern='examples'		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE=False		)    ->       Any:
  for pattern, fname in REPLACE_FILES.items():
    update_version_in_file(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
  if not patch:
    update_version_in_examples(_SCREAMING_SNAKE_CASE		)




def       __UpperCamelCase  ()    ->       str:
  lowercase__           =  '🤗 Transformers currently provides the following architectures'
  lowercase__           =  '1. Want to contribute a new model?'
  with open(_SCREAMING_SNAKE_CASE		,						'r'		,						encoding='utf-8'		,						newline='\n'		) as f:
    lowercase__           =  f.readlines()

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

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

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




def       __UpperCamelCase  ()    ->       Any:
  with open(REPLACE_FILES['init']		,						'r'		) as f:
    lowercase__           =  f.read()
  lowercase__           =  REPLACE_PATTERNS['init'][0].search(_SCREAMING_SNAKE_CASE		).groups()[0]
  return packaging.version.parse(_SCREAMING_SNAKE_CASE		)




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

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

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




def       __UpperCamelCase  ()    ->       int:
  lowercase__           =  get_version()
  lowercase__           =  F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
  lowercase__           =  current_version.base_version

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

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


if __name__ == "__main__":
      lowercase_          =		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.""")
      lowercase_          =		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()









import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
      from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       List[str]:
  if is_torch_version('<'		,						'2.0.0'		) or not hasattr(_SCREAMING_SNAKE_CASE		,						'_dynamo'		):
    return False
  return isinstance(_SCREAMING_SNAKE_CASE		,						torch._dynamo.eval_frame.OptimizedModule		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE = True		)    ->       Dict:
  lowercase__           =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

  lowercase__           =  is_compiled_module(_SCREAMING_SNAKE_CASE		)
  if is_compiled:
    lowercase__           =  model
    lowercase__           =  model._orig_mod

  if is_deepspeed_available():
    options += (DeepSpeedEngine,)

  while isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		):
    lowercase__           =  model.module

  if not keep_fpaa_wrapper:
    lowercase__           =  getattr(_SCREAMING_SNAKE_CASE		,						'forward'		)
    lowercase__           =  model.__dict__.pop('_original_forward'		,						_SCREAMING_SNAKE_CASE		)
    if original_forward is not None:
      while hasattr(_SCREAMING_SNAKE_CASE		,						'__wrapped__'		):
        lowercase__           =  forward.__wrapped__
        if forward == original_forward:
          break
      lowercase__           =  forward
    if getattr(_SCREAMING_SNAKE_CASE		,						'_converted_to_transformer_engine'		,						_SCREAMING_SNAKE_CASE		):
      convert_model(_SCREAMING_SNAKE_CASE		,						to_transformer_engine=_SCREAMING_SNAKE_CASE		)

  if is_compiled:
    lowercase__           =  model
    lowercase__           =  compiled_model

  return model




def       __UpperCamelCase  ()    ->       Tuple:
  PartialState().wait_for_everyone()




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       List[Any]:
  if PartialState().distributed_type == DistributedType.TPU:
    xm.save(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
  elif PartialState().local_process_index == 0:
    torch.save(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)




@contextmanager
def       __UpperCamelCase  (**_SCREAMING_SNAKE_CASE		)    ->       Optional[Any]:
  for key, value in kwargs.items():
    lowercase__           =  str(_SCREAMING_SNAKE_CASE		)

  yield

  for key in kwargs:
    if key.upper() in os.environ:
      del os.environ[key.upper()]




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       List[str]:
  if not hasattr(_SCREAMING_SNAKE_CASE		,						'__qualname__'		) and not hasattr(_SCREAMING_SNAKE_CASE		,						'__name__'		):
    lowercase__           =  getattr(_SCREAMING_SNAKE_CASE		,						'__class__'		,						_SCREAMING_SNAKE_CASE		)
  if hasattr(_SCREAMING_SNAKE_CASE		,						'__qualname__'		):
    return obj.__qualname__
  if hasattr(_SCREAMING_SNAKE_CASE		,						'__name__'		):
    return obj.__name__
  return str(_SCREAMING_SNAKE_CASE		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       Dict:
  for key, value in source.items():
    if isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		):
      lowercase__           =  destination.setdefault(_SCREAMING_SNAKE_CASE		,						{}		)
      merge_dicts(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
    else:
      lowercase__           =  value

  return destination




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE = None		)    ->       bool:
  if port is None:
    lowercase__           =  29500
  with socket.socket(socket.AF_INET		,						socket.SOCK_STREAM		) as s:
    return s.connect_ex(('localhost', port)		) == 0


