





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__    (							snake_case_	:  str       ,      snake_case_	:  Tuple=False       )      ->				Tuple:
   try:
      __snake_case							       =   os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      __snake_case							       =   default
   else:
      # KEY is set, convert it to True or False.
      try:
         __snake_case							       =   strtobool(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


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






def lowerCamelCase__    (							snake_case_	:  Tuple       )      ->				List[Any]:
   return unittest.skip('''Test was skipped'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       )      ->				Dict:
   return unittest.skipUnless(_run_slow_tests       ,      '''test is slow'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Tuple:
   return unittest.skipUnless(not torch.cuda.is_available()       ,      '''test requires only a CPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Tuple       )      ->				Optional[int]:
   return unittest.skipUnless(torch.cuda.is_available()       ,      '''test requires a GPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Union[str, Any]:
   return unittest.skipUnless(is_xpu_available()       ,      '''test requires a XPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Dict       )      ->				List[Any]:
   return unittest.skipUnless(is_mps_available()       ,      '''test requires a `mps` backend support in `torch`'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       )      ->				Dict:
   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available()       ,      '''test requires the Hugging Face suite'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Optional[Any]       )      ->				List[Any]:
   return unittest.skipUnless(is_bnb_available()       ,      '''test requires the bitsandbytes library'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Tuple       )      ->				Optional[int]:
   return unittest.skipUnless(is_tpu_available()       ,      '''test requires TPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  List[Any]       )      ->				Union[str, Any]:
   return unittest.skipUnless(torch.cuda.device_count() == 1       ,      '''test requires a GPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Dict       )      ->				Optional[Any]:
   return unittest.skipUnless(torch.xpu.device_count() == 1       ,      '''test requires a XPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Dict       )      ->				Tuple:
   return unittest.skipUnless(torch.cuda.device_count() > 1       ,      '''test requires multiple GPUs'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       )      ->				Tuple:
   return unittest.skipUnless(torch.xpu.device_count() > 1       ,      '''test requires multiple XPUs'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  List[Any]       )      ->				Dict:
   return unittest.skipUnless(is_safetensors_available()       ,      '''test requires safetensors'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  List[str]       )      ->				Any:
   return unittest.skipUnless(is_deepspeed_available()       ,      '''test requires DeepSpeed'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Optional[int]       )      ->				Tuple:
   return unittest.skipUnless(is_torch_version('''>='''       ,      '''1.12.0'''       )       ,      '''test requires torch version >= 1.12.0'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str=None       ,      snake_case_	:  Union[str, Any]=None       )      ->				int:
   if test_case is None:
      return partial(snake_case_       ,      version=snake_case_       )
   return unittest.skipUnless(is_torch_version('''>='''       ,      snake_case_       )       ,      f"""test requires torch version >= {version}"""       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  int       )      ->				Tuple:
   return unittest.skipUnless(is_tensorboard_available()       ,      '''test requires Tensorboard'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Optional[Any]:
   return unittest.skipUnless(is_wandb_available()       ,      '''test requires wandb'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Dict:
   return unittest.skipUnless(is_comet_ml_available()       ,      '''test requires comet_ml'''       )(snake_case_       )


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






def lowerCamelCase__    (							snake_case_	:  int       )      ->				Tuple:
   return unittest.skipUnless(
       _atleast_one_tracker_available       ,      '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''       ,      )(snake_case_       )

class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):
      A_						:				Optional[Any]							=    True


      @classmethod
      def    a (cls       :      int      ):





         """simple docstring"""



         __snake_case							       =   tempfile.mkdtemp()


      @classmethod
      def    a (cls       :      List[str]      ):





         """simple docstring"""



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


      def    a (self       :      str      ):





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






class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def    a (self       :      Optional[Any]      ):





         """simple docstring"""



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






class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def    a (self       :      Optional[int]				,			a__       :      Union[mock.Mock, List[mock.Mock]]      ):





         """simple docstring"""



         __snake_case							       =   mocks if isinstance(a__				,			(tuple, list)      ) else [mocks]
         for m in self.mocks:
            m.start()
            self.addCleanup(m.stop      )






def lowerCamelCase__    (							snake_case_	:  int       )      ->				Dict:
   __snake_case							       =   AcceleratorState()
   __snake_case							       =   tensor[None].clone().to(state.device       )
   __snake_case							       =   gather(snake_case_       ).cpu()
   __snake_case							       =   tensor[0].cpu()
   for i in range(tensors.shape[0]       ):
      if not torch.equal(tensors[i]       ,      snake_case_       ):
         return False
   return True

class 		SCREAMING_SNAKE_CASE__				:


      def __init__(self       :      Tuple				,			a__       :      int				,			a__       :      Dict				,			a__       :      Optional[int]      ):





         """simple docstring"""



         __snake_case							       =   returncode
         __snake_case							       =   stdout
         __snake_case							       =   stderr






async def lowerCamelCase__    (							snake_case_	:  Tuple       ,      snake_case_	:  Tuple       )      ->				Optional[Any]:
   while True:
      __snake_case							       =   await stream.readline()
      if line:
         callback(snake_case_       )
      else:
         break






async def lowerCamelCase__    (							snake_case_	:  List[Any]       ,      snake_case_	:  Union[str, Any]=None       ,      snake_case_	:  Tuple=None       ,      snake_case_	:  Tuple=None       ,      snake_case_	:  int=False       ,      snake_case_	:  Any=False       )      ->				_RunOutput:
   if echo:
      print('''\nRunning: '''       ,      ''' '''.join(snake_case_       )       )

   __snake_case							       =   await asyncio.create_subprocess_exec(
       cmd[0]       ,      *cmd[1:]       ,      stdin=snake_case_       ,      stdout=asyncio.subprocess.PIPE       ,      stderr=asyncio.subprocess.PIPE       ,      env=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)

   __snake_case							       =   []
   __snake_case							       =   []

   def tee(snake_case_	:  Dict       ,      snake_case_	:  str       ,      snake_case_	:  str       ,      snake_case_	:  Dict=""       ):
      __snake_case							       =   line.decode('''utf-8'''       ).rstrip()
      sink.append(snake_case_       )
      if not quiet:
         print(snake_case_       ,      snake_case_       ,      file=snake_case_       )

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






def lowerCamelCase__    (							snake_case_	:  Tuple       ,      snake_case_	:  Union[str, Any]=None       ,      snake_case_	:  Union[str, Any]=None       ,      snake_case_	:  Optional[int]=180       ,      snake_case_	:  Optional[int]=False       ,      snake_case_	:  str=True       )      ->				_RunOutput:
   __snake_case							       =   asyncio.get_event_loop()
   __snake_case							       =   loop.run_until_complete(
       _stream_subprocess(snake_case_       ,      env=snake_case_       ,      stdin=snake_case_       ,      timeout=snake_case_       ,      quiet=snake_case_       ,      echo=snake_case_       )       )

   __snake_case							       =   ''' '''.join(snake_case_       )
   if result.returncode > 0:
      __snake_case							       =   '''\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__				(       _UpperCAmelCase  ):
      pass






def lowerCamelCase__    (							snake_case_	:  List[str]       ,      snake_case_	:  List[str]=False       )      ->				Tuple:
   try:
      __snake_case							       =   subprocess.check_output(snake_case_       ,      stderr=subprocess.STDOUT       )
      if return_stdout:
         if hasattr(snake_case_       ,      '''decode'''       ):
            __snake_case							       =   output.decode('''utf-8'''       )
         return output
   except subprocess.CalledProcessError as e:
      raise SubprocessCallException(
          f"""Command `{' '.join(snake_case_       )}` failed with the following error:\n\n{e.output.decode()}"""       ) from e








from math import loga






def lowerCamelCase__    (							snake_case_	:  int       )      ->				int:
   if a < 0:
      raise ValueError('''Input value must be a positive integer'''       )
   elif isinstance(snake_case_       ,      snake_case_       ):
      raise TypeError('''Input value must be a \'int\' type'''       )
   return 0 if (a == 0) else int(loga(a & -a       )       )


if __name__ == "__main__":
    import doctest

    doctest.testmod()

