



"""simple docstring"""




import argparse
import os
import re

import packaging.version


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

def 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Optional[Any]		,    SCREAMING_SNAKE_CASE__      :		int		,    SCREAMING_SNAKE_CASE__      :		Union[str, Any]							)    ->  List[Any]:





     '''simple docstring'''

     with open(SCREAMING_SNAKE_CASE__		,    "r"		,    encoding="utf-8"		,    newline="\n"							) as f:
          _UpperCAmelCase     :      str														=       f.read()
     _UpperCAmelCase							,			_UpperCAmelCase     :      List[Any]														=       REPLACE_PATTERNS[pattern]
     _UpperCAmelCase     :      List[Any]														=       replace.replace("VERSION"		,    SCREAMING_SNAKE_CASE__							)
     _UpperCAmelCase     :      Dict														=       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 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Tuple							)    ->  Union[str, Any]:





     '''simple docstring'''

     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 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Any		,    SCREAMING_SNAKE_CASE__      :		str=False							)    ->  Union[str, Any]:





     '''simple docstring'''

     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 		__snake_case		( )    ->  List[Any]:





     '''simple docstring'''

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

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

     _UpperCAmelCase     :      Optional[int]														=       start_index
     # Update the lines in the model list.
     while not lines[index].startswith(_end_prompt							):
          if lines[index].startswith("1."							):
               _UpperCAmelCase     :      str														=       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 		__snake_case		( )    ->  Tuple:





     '''simple docstring'''

     with open(REPLACE_FILES["init"]		,    "r"							) as f:
          _UpperCAmelCase     :      Union[str, Any]														=       f.read()
     _UpperCAmelCase     :      str														=       REPLACE_PATTERNS["init"][0].search(SCREAMING_SNAKE_CASE__							).groups()[0]
     return packaging.version.parse(SCREAMING_SNAKE_CASE__							)

def 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Union[str, Any]=False							)    ->  Tuple:





     '''simple docstring'''

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

     # Now let's ask nicely if that's the right one.
     _UpperCAmelCase     :      Optional[int]														=       input(f'Which version are you releasing? [{default_version}]'							)
     if len(SCREAMING_SNAKE_CASE__							) == 0:
          _UpperCAmelCase     :      Union[str, Any]														=       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 		__snake_case		( )    ->  Optional[int]:





     '''simple docstring'''

     _UpperCAmelCase     :      Any														=       get_version()
     _UpperCAmelCase     :      Tuple														=       f'{current_version.major}.{current_version.minor + 1}.0.dev0'
     _UpperCAmelCase     :      Union[str, Any]														=       current_version.base_version

     # Check with the user we got that right.
     _UpperCAmelCase     :      List[Any]														=       input(f'Which version are we developing now? [{dev_version}]'							)
     if len(SCREAMING_SNAKE_CASE__							) == 0:
          _UpperCAmelCase     :      int														=       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__":
 _lowerCAmelCase							:   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 os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device


if is_torch_available():
 from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments






@require_torch
class       UpperCAmelCase_    (							unittest.TestCase		):



      def 		snake_case_   (	self	:      Union[str, Any]	,      A	:      Optional[Any]		):
           for model_result in results.values():
                for batch_size, sequence_length in zip(model_result["bs"]	,      model_result["ss"]		):
                     _UpperCAmelCase     :      List[str]														=       model_result["result"][batch_size][sequence_length]
                     self.assertIsNotNone(A		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Any														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      int														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      List[Any]														=       PyTorchBenchmark(A		)
           _UpperCAmelCase     :      List[Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      def 		snake_case_   (	self	:      Dict		):
           _UpperCAmelCase     :      List[str]														=       "sgugger/tiny-distilbert-classification"
           _UpperCAmelCase     :      Optional[int]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      only_pretrain_model=A	,      )
           _UpperCAmelCase     :      Dict														=       PyTorchBenchmark(A		)
           _UpperCAmelCase     :      Optional[Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      def 		snake_case_   (	self	:      int		):
           _UpperCAmelCase     :      Any														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      List[Any]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      torchscript=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      Dict														=       PyTorchBenchmark(A		)
           _UpperCAmelCase     :      Optional[Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      @unittest.skipIf(torch_device == "cpu"	,      "Cant do half precision"		)
      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase     :      Union[str, Any]														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      Optional[Any]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      fpaa=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      List[str]														=       PyTorchBenchmark(A		)
           _UpperCAmelCase     :      List[Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      Optional[Any]														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      int														=       AutoConfig.from_pretrained(A		)
           # set architectures equal to `None`
           _UpperCAmelCase     :      Optional[Any]														=       None
           _UpperCAmelCase     :      Optional[Any]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      List[Any]														=       PyTorchBenchmark(A	,      configs=[config]		)
           _UpperCAmelCase     :      Optional[Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      def 		snake_case_   (	self	:      int		):
           _UpperCAmelCase     :      Dict														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      Union[str, Any]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      Tuple														=       PyTorchBenchmark(A		)
           _UpperCAmelCase     :      Union[str, Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_train_result		)
           self.check_results_dict_not_empty(results.memory_train_result		)



      @unittest.skipIf(torch_device == "cpu"	,      "Can't do half precision"		)
      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      Optional[int]														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      str														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      fpaa=A	,      multi_process=A	,      )
           _UpperCAmelCase     :      Tuple														=       PyTorchBenchmark(A		)
           _UpperCAmelCase     :      List[Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_train_result		)
           self.check_results_dict_not_empty(results.memory_train_result		)



      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase     :      Optional[Any]														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      Union[str, Any]														=       AutoConfig.from_pretrained(A		)
           _UpperCAmelCase     :      Dict														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      List[Any]														=       PyTorchBenchmark(A	,      configs=[config]		)
           _UpperCAmelCase     :      List[str]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      List[str]														=       "sshleifer/tinier_bart"
           _UpperCAmelCase     :      Any														=       AutoConfig.from_pretrained(A		)
           _UpperCAmelCase     :      Optional[int]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      int														=       PyTorchBenchmark(A	,      configs=[config]		)
           _UpperCAmelCase     :      Union[str, Any]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_inference_result		)
           self.check_results_dict_not_empty(results.memory_inference_result		)



      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      Tuple														=       "sshleifer/tiny-gpt2"
           _UpperCAmelCase     :      Tuple														=       AutoConfig.from_pretrained(A		)
           _UpperCAmelCase     :      List[Any]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      int														=       PyTorchBenchmark(A	,      configs=[config]		)
           _UpperCAmelCase     :      Optional[int]														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_train_result		)
           self.check_results_dict_not_empty(results.memory_train_result		)



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      Optional[int]														=       "sshleifer/tinier_bart"
           _UpperCAmelCase     :      int														=       AutoConfig.from_pretrained(A		)
           _UpperCAmelCase     :      List[Any]														=       PyTorchBenchmarkArguments(
               models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      multi_process=A	,      )
           _UpperCAmelCase     :      str														=       PyTorchBenchmark(A	,      configs=[config]		)
           _UpperCAmelCase     :      int														=       benchmark.run()
           self.check_results_dict_not_empty(results.time_train_result		)
           self.check_results_dict_not_empty(results.memory_train_result		)



      def 		snake_case_   (	self	:      Dict		):
           _UpperCAmelCase     :      int														=       "sshleifer/tiny-gpt2"
           with tempfile.TemporaryDirectory() as tmp_dir:
                _UpperCAmelCase     :      Union[str, Any]														=       PyTorchBenchmarkArguments(
                    models=[MODEL_ID]	,      training=A	,      inference=A	,      save_to_csv=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      inference_time_csv_file=os.path.join(A	,      "inf_time.csv"		)	,      train_memory_csv_file=os.path.join(A	,      "train_mem.csv"		)	,      inference_memory_csv_file=os.path.join(A	,      "inf_mem.csv"		)	,      train_time_csv_file=os.path.join(A	,      "train_time.csv"		)	,      env_info_csv_file=os.path.join(A	,      "env.csv"		)	,      multi_process=A	,      )
                _UpperCAmelCase     :      int														=       PyTorchBenchmark(A		)
                benchmark.run()
                self.assertTrue(Path(os.path.join(A	,      "inf_time.csv"		)		).exists()		)
                self.assertTrue(Path(os.path.join(A	,      "train_time.csv"		)		).exists()		)
                self.assertTrue(Path(os.path.join(A	,      "inf_mem.csv"		)		).exists()		)
                self.assertTrue(Path(os.path.join(A	,      "train_mem.csv"		)		).exists()		)
                self.assertTrue(Path(os.path.join(A	,      "env.csv"		)		).exists()		)



      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase     :      List[Any]														=       "sshleifer/tiny-gpt2"

           def _check_summary_is_not_empty(A	:      int		):
                self.assertTrue(hasattr(A	,      "sequential"		)		)
                self.assertTrue(hasattr(A	,      "cumulative"		)		)
                self.assertTrue(hasattr(A	,      "current"		)		)
                self.assertTrue(hasattr(A	,      "total"		)		)

           with tempfile.TemporaryDirectory() as tmp_dir:
                _UpperCAmelCase     :      int														=       PyTorchBenchmarkArguments(
                    models=[MODEL_ID]	,      training=A	,      inference=A	,      sequence_lengths=[8]	,      batch_sizes=[1]	,      log_filename=os.path.join(A	,      "log.txt"		)	,      log_print=A	,      trace_memory_line_by_line=A	,      multi_process=A	,      )
                _UpperCAmelCase     :      int														=       PyTorchBenchmark(A		)
                _UpperCAmelCase     :      Any														=       benchmark.run()
                _check_summary_is_not_empty(result.inference_summary		)
                _check_summary_is_not_empty(result.train_summary		)
                self.assertTrue(Path(os.path.join(A	,      "log.txt"		)		).exists()		)
