


"""simple docstring"""



import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment







def 						__lowerCAmelCase		(		lowercase						:						List[str]		,							lowercase						:						Any=()		,							lowercase						:						str=None		,							lowercase						:						Dict="no"		,							lowercase						:						Optional[int]="29500"				)			->		List[str]:


    """simple docstring"""





    snake_case					:   Tuple         =					False
    snake_case					:   Dict         =					False
    if any(key.startswith("KAGGLE"				) for key in os.environ.keys()				):
        snake_case					:   List[Any]         =					True
    elif "IPython" in sys.modules:
        snake_case					:   Optional[Any]         =					"google.colab" in str(sys.modules["IPython"].get_ipython()				)

    try:
        snake_case					:   List[Any]         =					PrecisionType(mixed_precision.lower()				)
    except ValueError:
        raise ValueError(
            F'Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'				)

    if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME"		,							__A				) is not None):
        # TPU launch
        import torch_xla.distributed.xla_multiprocessing as xmp

        if len(AcceleratorState._shared_state				) > 0:
            raise ValueError(
                "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
                "your training function. Restart your notebook and make sure no cells initializes an "
                "`Accelerator`."				)
        if num_processes is None:
            snake_case					:   Optional[int]         =					8

        snake_case					:   Union[str, Any]         =					PrepareForLaunch(__A		,							distributed_type="TPU"				)
        print(F'Launching a training on {num_processes} TPU cores.'				)
        xmp.spawn(__A		,							args=__A		,							nprocs=__A		,							start_method="fork"				)
    elif in_colab:
        # No need for a distributed launch otherwise as it's either CPU or one GPU.
        if torch.cuda.is_available():
            print("Launching training on one GPU."				)
        else:
            print("Launching training on one CPU."				)
        function(*__A				)
    else:
        if num_processes is None:
            raise ValueError(
                "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."				)

        if num_processes > 1:
            # Multi-GPU launch
            from torch.multiprocessing import start_processes
            from torch.multiprocessing.spawn import ProcessRaisedException

            if len(AcceleratorState._shared_state				) > 0:
                raise ValueError(
                    "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
                    "inside your training function. Restart your notebook and make sure no cells initializes an "
                    "`Accelerator`."				)

            if torch.cuda.is_initialized():
                raise ValueError(
                    "To launch a multi-GPU training from your notebook, you need to avoid running any instruction "
                    "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA "
                    "function."				)

            # torch.distributed will expect a few environment variable to be here. We set the ones common to each
            # process here (the other ones will be set be the launcher).
            with patch_environment(
                world_size=__A		,							master_addr="127.0.01"		,							master_port=__A		,							mixed_precision=__A				):
                snake_case					:   Optional[Any]         =					PrepareForLaunch(__A		,							distributed_type="MULTI_GPU"				)
                print(F'Launching training on {num_processes} GPUs.'				)
                try:
                    start_processes(__A		,							args=__A		,							nprocs=__A		,							start_method="fork"				)
                except ProcessRaisedException as e:
                    if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
                        raise RuntimeError(
                            "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
                            "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
                            "Please review your imports and test them when running the `notebook_launcher()` to identify "
                            "which one is problematic."				) from e

        else:
            # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
            if is_mps_available():
                snake_case					:   Dict         =					"1"
                print("Launching training on MPS."				)
            elif torch.cuda.is_available():
                print("Launching training on one GPU."				)
            else:
                print("Launching training on CPU."				)
            function(*__A				)







def 						__lowerCAmelCase		(		lowercase						:						Union[str, Any]		,							lowercase						:						Any=()		,							lowercase						:						Union[str, Any]=2				)			->		Tuple:


    """simple docstring"""





    from torch.multiprocessing import start_processes

    with tempfile.NamedTemporaryFile() as tmp_file:
        # torch.distributed will expect a few environment variable to be here. We set the ones common to each
        # process here (the other ones will be set be the launcher).
        with patch_environment(
            world_size=__A		,							master_addr="127.0.01"		,							master_port="29500"		,							accelerate_mixed_precision="no"		,							accelerate_debug_rdv_file=tmp_file.name		,							accelerate_use_cpu="yes"		,							):
            snake_case					:   Tuple         =					PrepareForLaunch(__A		,							debug=__A				)
            start_processes(__A		,							args=__A		,							nprocs=__A		,							start_method="fork"				)



"""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 _lowerCAmelCase       (   unittest.TestCase			):







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Dict:

       '''simple docstring'''




       for model_result in results.values():
           for batch_size, sequence_length in zip(model_result["bs"]		,			model_result["ss"]		):
               snake_case					:   Optional[int]         =					model_result["result"][batch_size][sequence_length]
               self.assertIsNotNone(UpperCamelCase__		)







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   List[Any]         =					"sshleifer/tiny-gpt2"
       snake_case					:   List[Any]         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   Dict         =					PyTorchBenchmark(UpperCamelCase__		)
       snake_case					:   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 				lowerCamelCase	(			self		)			->	Union[str, Any]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		)			->	List[str]:

       '''simple docstring'''




       snake_case					:   List[Any]         =					"sshleifer/tiny-gpt2"
       snake_case					:   Tuple         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			torchscript=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   int         =					PyTorchBenchmark(UpperCamelCase__		)
       snake_case					:   int         =					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 				lowerCamelCase	(			self		)			->	Optional[Any]:

       '''simple docstring'''




       snake_case					:   List[Any]         =					"sshleifer/tiny-gpt2"
       snake_case					:   int         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			fpaa=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   List[Any]         =					PyTorchBenchmark(UpperCamelCase__		)
       snake_case					:   str         =					benchmark.run()
       self.check_results_dict_not_empty(results.time_inference_result		)
       self.check_results_dict_not_empty(results.memory_inference_result		)







   def 				lowerCamelCase	(			self		)			->	List[str]:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					"sshleifer/tiny-gpt2"
       snake_case					:   int         =					AutoConfig.from_pretrained(UpperCamelCase__		)
       # set architectures equal to `None`
       snake_case					:   str         =					None
       snake_case					:   List[Any]         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   List[Any]         =					PyTorchBenchmark(UpperCamelCase__		,			configs=[config]		)
       snake_case					:   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 				lowerCamelCase	(			self		)			->	Dict:

       '''simple docstring'''




       snake_case					:   Tuple         =					"sshleifer/tiny-gpt2"
       snake_case					:   str         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   List[str]         =					PyTorchBenchmark(UpperCamelCase__		)
       snake_case					:   Dict         =					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 				lowerCamelCase	(			self		)			->	int:

       '''simple docstring'''




       snake_case					:   Optional[Any]         =					"sshleifer/tiny-gpt2"
       snake_case					:   Optional[Any]         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			fpaa=UpperCamelCase__		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   Optional[int]         =					PyTorchBenchmark(UpperCamelCase__		)
       snake_case					:   str         =					benchmark.run()
       self.check_results_dict_not_empty(results.time_train_result		)
       self.check_results_dict_not_empty(results.memory_train_result		)







   def 				lowerCamelCase	(			self		)			->	Optional[int]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					"sshleifer/tinier_bart"
       snake_case					:   List[str]         =					AutoConfig.from_pretrained(UpperCamelCase__		)
       snake_case					:   Optional[int]         =					PyTorchBenchmarkArguments(
           models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			multi_process=UpperCamelCase__		,			)
       snake_case					:   Union[str, Any]         =					PyTorchBenchmark(UpperCamelCase__		,			configs=[config]		)
       snake_case					:   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 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		)			->	Optional[int]:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   Union[str, Any]         =					"sshleifer/tiny-gpt2"

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

       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case					:   Tuple         =					PyTorchBenchmarkArguments(
               models=[MODEL_ID]		,			training=UpperCamelCase__		,			inference=UpperCamelCase__		,			sequence_lengths=[8]		,			batch_sizes=[1]		,			log_filename=os.path.join(UpperCamelCase__		,			"log.txt"		)		,			log_print=UpperCamelCase__		,			trace_memory_line_by_line=UpperCamelCase__		,			multi_process=UpperCamelCase__		,			)
           snake_case					:   Dict         =					PyTorchBenchmark(UpperCamelCase__		)
           snake_case					:   List[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(UpperCamelCase__		,			"log.txt"		)		).exists()		)





