






"""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 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=False ):




  """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(__UpperCamelCase )
    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


lowercase_				     =     parse_flag_from_env('RUN_SLOW', default=False)



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skip('''Test was skipped''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(_run_slow_tests		,       '''test is slow''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(not torch.cuda.is_available()		,       '''test requires only a CPU''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(torch.cuda.is_available()		,       '''test requires a GPU''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_xpu_available()		,       '''test requires a XPU''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_mps_available()		,       '''test requires a `mps` backend support in `torch`''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(
      is_transformers_available() and is_datasets_available()		,       '''test requires the Hugging Face suite''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_bnb_available()		,       '''test requires the bitsandbytes library''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_tpu_available()		,       '''test requires TPU''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(torch.cuda.device_count() == 1		,       '''test requires a GPU''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(torch.xpu.device_count() == 1		,       '''test requires a XPU''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(torch.cuda.device_count() > 1		,       '''test requires multiple GPUs''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(torch.xpu.device_count() > 1		,       '''test requires multiple XPUs''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_safetensors_available()		,       '''test requires safetensors''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_deepspeed_available()		,       '''test requires DeepSpeed''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_torch_version('''>='''		,       '''1.12.0''' )		,       '''test requires torch version >= 1.12.0''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase=None		,       __UpperCamelCase=None ):




  """simple docstring"""







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



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_tensorboard_available()		,       '''test requires Tensorboard''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_wandb_available()		,       '''test requires wandb''' )(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  return unittest.skipUnless(is_comet_ml_available()		,       '''test requires comet_ml''' )(__UpperCamelCase )


lowercase_				     =     (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """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'''		,       )(__UpperCamelCase )


class 					snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   A_						:	str						 = True


   @classmethod
   def 				_SCREAMING_SNAKE_CASE				(	cls :     Tuple  ):

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


   @classmethod
   def 				_SCREAMING_SNAKE_CASE				(	cls :     Dict  ):

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






   def 				_SCREAMING_SNAKE_CASE				(	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 					snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str]  ):

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





class 					snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str],       _lowerCamelCase :     Union[mock.Mock, List[mock.Mock]]  ):

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





def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  __A									= AcceleratorState()
  __A									= tensor[None].clone().to(state.device )
  __A									= gather(__UpperCamelCase ).cpu()
  __A									= tensor[0].cpu()
  for i in range(tensors.shape[0] ):
    if not torch.equal(tensors[i]		,       __UpperCamelCase ):
      return False
  return True


class 					snake_case		:


   '''simple docstring'''

   def __init__(	self :     str,       _lowerCamelCase :     Union[str, Any],       _lowerCamelCase :     str,       _lowerCamelCase :     Union[str, Any]  ):

     '''simple docstring'''
     __A									= returncode
     __A									= stdout
     __A									= stderr





async def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







  while True:
    __A									= await stream.readline()
    if line:
      callback(__UpperCamelCase )
    else:
      break



async def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=None		,       __UpperCamelCase=None		,       __UpperCamelCase=None		,       __UpperCamelCase=False		,       __UpperCamelCase=False ):




  """simple docstring"""







  if echo:
    print('''\nRunning: '''		,       ''' '''.join(__UpperCamelCase ) )

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

  # 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(__UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase="" ):
    __A									= line.decode('''utf-8''' ).rstrip()
    sink.append(__UpperCamelCase )
    if not quiet:
      print(__UpperCamelCase		,       __UpperCamelCase		,       file=__UpperCamelCase )

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



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=None		,       __UpperCamelCase=None		,       __UpperCamelCase=1_8_0		,       __UpperCamelCase=False		,       __UpperCamelCase=True ):




  """simple docstring"""







  __A									= asyncio.get_event_loop()
  __A									= loop.run_until_complete(
      _stream_subprocess(__UpperCamelCase		,       env=__UpperCamelCase		,       stdin=__UpperCamelCase		,       timeout=__UpperCamelCase		,       quiet=__UpperCamelCase		,       echo=__UpperCamelCase ) )

  __A									= ''' '''.join(__UpperCamelCase )
  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 					snake_case		(							_lowerCAmelCase						):


   '''simple docstring'''

   pass





def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=False ):




  """simple docstring"""







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












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


   '''simple docstring'''

   def 				_SCREAMING_SNAKE_CASE				(	self :     Any,       _lowerCamelCase :     Optional[int]  ):

     '''simple docstring'''
     for model_result in results.values():
       for batch_size, sequence_length in zip(model_result['''bs'''],       model_result['''ss''']  ):
         __A									= model_result['''result'''][batch_size][sequence_length]
         self.assertIsNotNone(_lowerCamelCase  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_inference_result  )
     self.check_results_dict_not_empty(results.memory_inference_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     __A									= '''sgugger/tiny-distilbert-classification'''
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       only_pretrain_model=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_inference_result  )
     self.check_results_dict_not_empty(results.memory_inference_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Any  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       torchscript=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase  )
     __A									= 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 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       fpaa=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_inference_result  )
     self.check_results_dict_not_empty(results.memory_inference_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= AutoConfig.from_pretrained(_lowerCamelCase  )
     # set architectures equal to `None`
     __A									= None
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase,       configs=[config]  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_inference_result  )
     self.check_results_dict_not_empty(results.memory_inference_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     int  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase  )
     __A									= 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 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int]  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       fpaa=_lowerCamelCase,       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_train_result  )
     self.check_results_dict_not_empty(results.memory_train_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= AutoConfig.from_pretrained(_lowerCamelCase  )
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase,       configs=[config]  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_inference_result  )
     self.check_results_dict_not_empty(results.memory_inference_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     List[Any]  ):

     '''simple docstring'''
     __A									= '''sshleifer/tinier_bart'''
     __A									= AutoConfig.from_pretrained(_lowerCamelCase  )
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase,       configs=[config]  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_inference_result  )
     self.check_results_dict_not_empty(results.memory_inference_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''
     __A									= AutoConfig.from_pretrained(_lowerCamelCase  )
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase,       configs=[config]  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_train_result  )
     self.check_results_dict_not_empty(results.memory_train_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     __A									= '''sshleifer/tinier_bart'''
     __A									= AutoConfig.from_pretrained(_lowerCamelCase  )
     __A									= PyTorchBenchmarkArguments(
         models=[MODEL_ID],       training=_lowerCamelCase,       inference=_lowerCamelCase,       sequence_lengths=[8],       batch_sizes=[1],       multi_process=_lowerCamelCase,       )
     __A									= PyTorchBenchmark(_lowerCamelCase,       configs=[config]  )
     __A									= benchmark.run()
     self.check_results_dict_not_empty(results.time_train_result  )
     self.check_results_dict_not_empty(results.memory_train_result  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

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






   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     __A									= '''sshleifer/tiny-gpt2'''

     def _check_summary_is_not_empty(_lowerCamelCase :     List[Any]  ):
       self.assertTrue(hasattr(_lowerCamelCase,       '''sequential'''  )  )
       self.assertTrue(hasattr(_lowerCamelCase,       '''cumulative'''  )  )
       self.assertTrue(hasattr(_lowerCamelCase,       '''current'''  )  )
       self.assertTrue(hasattr(_lowerCamelCase,       '''total'''  )  )

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




