






'''simple docstring'''



import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[str],					SCREAMING_SNAKE_CASE__:	Union[str, Any]=False    )  ->			List[str]:

   """simple docstring"""
   try:
      __a				     =    os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      __a				     =    default
   else:
      # KEY is set, convert it to True or False.
      try:
         __a				     =    strtobool(SCREAMING_SNAKE_CASE__    )
      except ValueError:
         # More values are supported, but let's keep the message simple.
         raise ValueError(f"""If set, {key} must be yes or no."""    )
   return _value


__UpperCamelCase      :       Dict      			=      parse_flag_from_env("""RUN_SLOW""", default=False)



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Dict    )  ->			List[str]:

   """simple docstring"""
   return unittest.skip('Test was skipped'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	int    )  ->			Optional[Any]:

   """simple docstring"""
   return unittest.skipUnless(_run_slow_tests,					'test is slow'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[str]    )  ->			Tuple:

   """simple docstring"""
   return unittest.skipUnless(not torch.cuda.is_available(),					'test requires only a CPU'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Tuple    )  ->			List[Any]:

   """simple docstring"""
   return unittest.skipUnless(torch.cuda.is_available(),					'test requires a GPU'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Any    )  ->			str:

   """simple docstring"""
   return unittest.skipUnless(is_xpu_available(),					'test requires a XPU'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Optional[int]    )  ->			List[str]:

   """simple docstring"""
   return unittest.skipUnless(is_mps_available(),					'test requires a `mps` backend support in `torch`'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Tuple    )  ->			str:

   """simple docstring"""
   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available(),					'test requires the Hugging Face suite'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[Any]    )  ->			str:

   """simple docstring"""
   return unittest.skipUnless(is_bnb_available(),					'test requires the bitsandbytes library'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Dict    )  ->			str:

   """simple docstring"""
   return unittest.skipUnless(is_tpu_available(),					'test requires TPU'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[str]    )  ->			List[str]:

   """simple docstring"""
   return unittest.skipUnless(torch.cuda.device_count() == 1,					'test requires a GPU'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Dict    )  ->			int:

   """simple docstring"""
   return unittest.skipUnless(torch.xpu.device_count() == 1,					'test requires a XPU'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	str    )  ->			Optional[int]:

   """simple docstring"""
   return unittest.skipUnless(torch.cuda.device_count() > 1,					'test requires multiple GPUs'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[Any]    )  ->			List[Any]:

   """simple docstring"""
   return unittest.skipUnless(torch.xpu.device_count() > 1,					'test requires multiple XPUs'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Union[str, Any]    )  ->			Dict:

   """simple docstring"""
   return unittest.skipUnless(is_safetensors_available(),					'test requires safetensors'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	int    )  ->			Union[str, Any]:

   """simple docstring"""
   return unittest.skipUnless(is_deepspeed_available(),					'test requires DeepSpeed'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Union[str, Any]    )  ->			Any:

   """simple docstring"""
   return unittest.skipUnless(is_torch_version('>=',					'1.12.0'    ),					'test requires torch version >= 1.12.0'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[Any]=None,					SCREAMING_SNAKE_CASE__:	Tuple=None    )  ->			Optional[Any]:

   """simple docstring"""
   if test_case is None:
      return partial(SCREAMING_SNAKE_CASE__,					version=SCREAMING_SNAKE_CASE__    )
   return unittest.skipUnless(is_torch_version('>=',					SCREAMING_SNAKE_CASE__    ),					f"""test requires torch version >= {version}"""    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	str    )  ->			Tuple:

   """simple docstring"""
   return unittest.skipUnless(is_tensorboard_available(),					'test requires Tensorboard'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Optional[Any]    )  ->			Any:

   """simple docstring"""
   return unittest.skipUnless(is_wandb_available(),					'test requires wandb'    )(SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	int    )  ->			Dict:

   """simple docstring"""
   return unittest.skipUnless(is_comet_ml_available(),					'test requires comet_ml'    )(SCREAMING_SNAKE_CASE__    )


__UpperCamelCase      :       str      			=      (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Dict    )  ->			str:

   """simple docstring"""
   return unittest.skipUnless(
       _atleast_one_tracker_available,					'test requires at least one tracker to be available and for `comet_ml` to not be installed',					)(SCREAMING_SNAKE_CASE__    )
class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):
      __a  					=True




      @classmethod
      def  __UpperCamelCase							(  cls      )							->Any:



         '''simple docstring'''
         __a				     =    tempfile.mkdtemp()




      @classmethod
      def  __UpperCamelCase							(  cls      )							->Union[str, Any]:



         '''simple docstring'''
         if os.path.exists(cls.tmpdir      ):
            shutil.rmtree(cls.tmpdir      )






      def  __UpperCamelCase							(  self      )							->Optional[Any]:



         '''simple docstring'''
         if self.clear_on_setup:
            for path in Path(self.tmpdir      ).glob('**/*'      ):
               if path.is_file():
                  path.unlink()
               elif path.is_dir():
                  shutil.rmtree(lowerCamelCase      )







class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         super().tearDown()
         # Reset the state of the AcceleratorState singleton.
         AcceleratorState._reset_state()
         PartialState._reset_state()







class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      def  __UpperCamelCase							(  self ,   lowerCamelCase      )							->int:



         '''simple docstring'''
         __a				     =    mocks if isinstance(lowerCamelCase ,   (tuple, list)      ) else [mocks]
         for m in self.mocks:
            m.start()
            self.addCleanup(m.stop      )







def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Tuple    )  ->			List[Any]:

   """simple docstring"""
   __a				     =    AcceleratorState()
   __a				     =    tensor[None].clone().to(state.device    )
   __a				     =    gather(SCREAMING_SNAKE_CASE__    ).cpu()
   __a				     =    tensor[0].cpu()
   for i in range(tensors.shape[0]    ):
      if not torch.equal(tensors[i],					SCREAMING_SNAKE_CASE__    ):
         return False
   return True
class 							__SCREAMING_SNAKE_CASE       :




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



         '''simple docstring'''
         __a				     =    returncode
         __a				     =    stdout
         __a				     =    stderr







async def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Dict,					SCREAMING_SNAKE_CASE__:	Optional[int]    )  ->			Optional[Any]:

   """simple docstring"""
   while True:
      __a				     =    await stream.readline()
      if line:
         callback(SCREAMING_SNAKE_CASE__    )
      else:
         break



async def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	List[str],					SCREAMING_SNAKE_CASE__:	List[Any]=None,					SCREAMING_SNAKE_CASE__:	Any=None,					SCREAMING_SNAKE_CASE__:	Dict=None,					SCREAMING_SNAKE_CASE__:	int=False,					SCREAMING_SNAKE_CASE__:	List[str]=False    )  ->			_RunOutput:

   """simple docstring"""
   if echo:
      print('\nRunning: ',					' '.join(SCREAMING_SNAKE_CASE__    )    )

   __a				     =    await asyncio.create_subprocess_exec(
       cmd[0],					*cmd[1:],					stdin=SCREAMING_SNAKE_CASE__,					stdout=asyncio.subprocess.PIPE,					stderr=asyncio.subprocess.PIPE,					env=SCREAMING_SNAKE_CASE__,					)

   # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
   # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
   #
   # If it starts hanging, will need to switch to the following code. The problem is that no data
   # will be seen until it's done and if it hangs for example there will be no debug info.
   # out, err = await p.communicate()
   # return _RunOutput(p.returncode, out, err)

   __a				     =    []
   __a				     =    []

   def tee(SCREAMING_SNAKE_CASE__:	Union[str, Any],					SCREAMING_SNAKE_CASE__:	Optional[int],					SCREAMING_SNAKE_CASE__:	Dict,					SCREAMING_SNAKE_CASE__:	List[Any]=""    ):
      __a				     =    line.decode('utf-8'    ).rstrip()
      sink.append(SCREAMING_SNAKE_CASE__    )
      if not quiet:
         print(SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					file=SCREAMING_SNAKE_CASE__    )

    # XXX: the timeout doesn't seem to make any difference here
   await asyncio.wait(
       [
           asyncio.create_task(_read_stream(p.stdout,					lambda SCREAMING_SNAKE_CASE__    : tee(SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					sys.stdout,					label='stdout:'    )    )    ),
           asyncio.create_task(_read_stream(p.stderr,					lambda SCREAMING_SNAKE_CASE__    : tee(SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					sys.stderr,					label='stderr:'    )    )    ),
       ],					timeout=SCREAMING_SNAKE_CASE__,					)
   return _RunOutput(await p.wait(),					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__    )



def    __UpperCAmelCase	(				SCREAMING_SNAKE_CASE__:	Any,					SCREAMING_SNAKE_CASE__:	Optional[int]=None,					SCREAMING_SNAKE_CASE__:	List[str]=None,					SCREAMING_SNAKE_CASE__:	Tuple=180,					SCREAMING_SNAKE_CASE__:	Optional[int]=False,					SCREAMING_SNAKE_CASE__:	Optional[Any]=True    )  ->			_RunOutput:

   """simple docstring"""
   __a				     =    asyncio.get_event_loop()
   __a				     =    loop.run_until_complete(
       _stream_subprocess(SCREAMING_SNAKE_CASE__,					env=SCREAMING_SNAKE_CASE__,					stdin=SCREAMING_SNAKE_CASE__,					timeout=SCREAMING_SNAKE_CASE__,					quiet=SCREAMING_SNAKE_CASE__,					echo=SCREAMING_SNAKE_CASE__    )    )

   __a				     =    ' '.join(SCREAMING_SNAKE_CASE__    )
   if result.returncode > 0:
      __a				     =    '\n'.join(result.stderr    )
      raise RuntimeError(
          f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
          f"""The combined stderr from workers follows:\n{stderr}"""    )

   return result
class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):
      pass







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

   """simple docstring"""
   try:
      __a				     =    subprocess.check_output(SCREAMING_SNAKE_CASE__,					stderr=subprocess.STDOUT    )
      if return_stdout:
         if hasattr(SCREAMING_SNAKE_CASE__,					'decode'    ):
            __a				     =    output.decode('utf-8'    )
         return output
   except subprocess.CalledProcessError as e:
      raise SubprocessCallException(
          f"""Command `{" ".join(SCREAMING_SNAKE_CASE__    )}` failed with the following error:\n\n{e.output.decode()}"""    ) from e







'''simple docstring'''



from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
 import torch

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


__UpperCamelCase      :       Optional[Any]      			=      logging.get_logger(__name__)
@dataclass
class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase     ):
      __a  					=[
          "no_inference",
          "no_cuda",
          "no_tpu",
          "no_speed",
          "no_memory",
          "no_env_print",
          "no_multi_process",
      ]




      def __init__(  self ,   **lowerCamelCase      )							->List[Any]:



         '''simple docstring'''
         for deprecated_arg in self.deprecated_args:
            if deprecated_arg in kwargs:
               __a				     =    deprecated_arg[3:]
               setattr(self ,   lowerCamelCase ,   not kwargs.pop(lowerCamelCase      )      )
               logger.warning(
                   F"""{deprecated_arg} is depreciated. Please use --no_{positive_arg} or"""
                   F""" {positive_arg}={kwargs[positive_arg]}"""      )

         __a				     =    kwargs.pop('torchscript' ,   self.torchscript      )
         __a				     =    kwargs.pop('torch_xla_tpu_print_metrics' ,   self.torch_xla_tpu_print_metrics      )
         __a				     =    kwargs.pop('fp16_opt_level' ,   self.fpaa_opt_level      )
         super().__init__(**lowerCamelCase      )

      __a  					=field(default=_lowerCAmelCase      ,      metadata={"help": "Trace the models using torchscript"}     )
      __a  					=field(default=_lowerCAmelCase      ,      metadata={"help": "Print Xla/PyTorch tpu metrics"}     )
      __a  					=field(
          default="O1"      ,      metadata={
              "help": (
                  "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
                  "See details at https://nvidia.github.io/apex/amp.html"
              )
          }      ,      )




      @cached_property
      def  __UpperCamelCase							(  self      )							->Tuple["torch.device", int]:



         '''simple docstring'''
         requires_backends(self ,   ['torch']      )
         logger.info('PyTorch: setting up devices'      )
         if not self.cuda:
            __a				     =    torch.device('cpu'      )
            __a				     =    0
         elif is_torch_tpu_available():
            __a				     =    xm.xla_device()
            __a				     =    0
         else:
            __a				     =    torch.device('cuda' if torch.cuda.is_available() else 'cpu'      )
            __a				     =    torch.cuda.device_count()
         return device, n_gpu




      @property
      def  __UpperCamelCase							(  self      )							->Optional[Any]:



         '''simple docstring'''
         return is_torch_tpu_available() and self.tpu




      @property
      def  __UpperCamelCase							(  self      )							->int:



         '''simple docstring'''
         requires_backends(self ,   ['torch']      )
         # TODO(PVP): currently only single GPU is supported
         return torch.cuda.current_device()




      @property
      def  __UpperCamelCase							(  self      )							->"torch.device":



         '''simple docstring'''
         requires_backends(self ,   ['torch']      )
         return self._setup_devices[0]




      @property
      def  __UpperCamelCase							(  self      )							->List[Any]:



         '''simple docstring'''
         requires_backends(self ,   ['torch']      )
         return self._setup_devices[1]






      @property
      def  __UpperCamelCase							(  self      )							->List[str]:



         '''simple docstring'''
         return self.n_gpu > 0