



"""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      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase=False )   ->	Tuple:






      '''simple docstring'''


      try:
            lowercase     :					Union[str, Any] 		=      os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            lowercase     :					List[str] 		=      default
      else:
            # KEY is set, convert it to True or False.
            try:
                  lowercase     :					List[str] 		=      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


_UpperCamelCase: Dict										=     parse_flag_from_env('RUN_SLOW', default=False)


def      lowercase__   (	_UpperCAmelCase )   ->	Optional[Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Any:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Optional[int]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Optional[Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Tuple:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	List[Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Union[str, Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Union[str, Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Union[str, Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Optional[Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Any:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	List[str]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Any:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Union[str, Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Dict:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	List[str]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase=None		,					_UpperCAmelCase=None )   ->	Union[str, Any]:






      '''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      lowercase__   (	_UpperCAmelCase )   ->	Optional[Any]:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Dict:






      '''simple docstring'''


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


def      lowercase__   (	_UpperCAmelCase )   ->	Union[str, Any]:






      '''simple docstring'''


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


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


def      lowercase__   (	_UpperCAmelCase )   ->	Dict:






      '''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      a__						(  unittest.TestCase   ):
   _lowerCamelCase    							= True


   @classmethod
   def 				lowercase (							cls					:							Dict	)			->				Optional[Any]:
         lowercase     :					List[Any] 		=      tempfile.mkdtemp()


   @classmethod
   def 				lowercase (							cls					:							Any	)			->				List[Any]:
         if os.path.exists(cls.tmpdir	):
               shutil.rmtree(cls.tmpdir	)






   def 				lowercase (							self					:							int	)			->				int:
         if self.clear_on_setup:
               for path in Path(self.tmpdir	).glob('**/*'	):
                     if path.is_file():
                           path.unlink()
                     elif path.is_dir():
                           shutil.rmtree(UpperCAmelCase_	)




class      a__						(  unittest.TestCase   ):


   def 				lowercase (							self					:							Union[str, Any]	)			->				Dict:
         super().tearDown()
         # Reset the state of the AcceleratorState singleton.
         AcceleratorState._reset_state()
         PartialState._reset_state()




class      a__						(  unittest.TestCase   ):


   def 				lowercase (							self					:							List[Any],   lowerCAmelCase					:							Union[mock.Mock, List[mock.Mock]]	)			->				List[str]:
         lowercase     :					Union[str, Any] 		=      mocks if isinstance(UpperCAmelCase_,   (tuple, list)	) else [mocks]
         for m in self.mocks:
               m.start()
               self.addCleanup(m.stop	)




def      lowercase__   (	_UpperCAmelCase )   ->	Optional[Any]:






      '''simple docstring'''


      lowercase     :					Union[str, Any] 		=      AcceleratorState()
      lowercase     :					Optional[Any] 		=      tensor[None].clone().to(state.device )
      lowercase     :					Union[str, Any] 		=      gather(UpperCamelCase_ ).cpu()
      lowercase     :					Tuple 		=      tensor[0].cpu()
      for i in range(tensors.shape[0] ):
            if not torch.equal(tensors[i]		,					UpperCamelCase_ ):
                  return False
      return True


class      a__						:


   def __init__(							self					:							Optional[int],   lowerCAmelCase					:							str,   lowerCAmelCase					:							Any,   lowerCAmelCase					:							List[Any]	)			->				Dict:
         lowercase     :					List[str] 		=      returncode
         lowercase     :					int 		=      stdout
         lowercase     :					Optional[Any] 		=      stderr




async def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase )   ->	int:






      '''simple docstring'''


      while True:
            lowercase     :					str 		=      await stream.readline()
            if line:
                  callback(UpperCamelCase_ )
            else:
                  break


async def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase=None		,					_UpperCAmelCase=None		,					_UpperCAmelCase=None		,					_UpperCAmelCase=False		,					_UpperCAmelCase=False )   ->	_RunOutput:






      '''simple docstring'''


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

      lowercase     :					str 		=      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)

      lowercase     :					Any 		=      []
      lowercase     :					Optional[Any] 		=      []

      def tee(_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase="" ):
            lowercase     :					Optional[Any] 		=      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      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase=None		,					_UpperCAmelCase=None		,					_UpperCAmelCase=1_80		,					_UpperCAmelCase=False		,					_UpperCAmelCase=True )   ->	_RunOutput:






      '''simple docstring'''


      lowercase     :					Union[str, Any] 		=      asyncio.get_event_loop()
      lowercase     :					Optional[int] 		=      loop.run_until_complete(
          _stream_subprocess(UpperCamelCase_		,					env=UpperCamelCase_		,					stdin=UpperCamelCase_		,					timeout=UpperCamelCase_		,					quiet=UpperCamelCase_		,					echo=UpperCamelCase_ ) )

      lowercase     :					Dict 		=      ' '.join(UpperCamelCase_ )
      if result.returncode > 0:
            lowercase     :					Dict 		=      '\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      a__						(  _UpperCAmelCase   ):
   pass




def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase=False )   ->	Any:






      '''simple docstring'''


      try:
            lowercase     :					Any 		=      subprocess.check_output(UpperCamelCase_		,					stderr=subprocess.STDOUT )
            if return_stdout:
                  if hasattr(UpperCamelCase_		,					'decode' ):
                        lowercase     :					Union[str, Any] 		=      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


def 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_		)		->		str:
					'''simple docstring'''


					if not isinstance(UpperCamelCase_	,	UpperCamelCase_		):
										raise ValueError('iterations must be defined as integers'		)
					if not isinstance(UpperCamelCase_	,	UpperCamelCase_		) or not number >= 1:
										raise ValueError(
										    'starting number must be\n                         and integer and be more than 0'		)
					if not iterations >= 1:
										raise ValueError('Iterations must be done more than 0 times to play FizzBuzz'		)

					SCREAMING_SNAKE_CASE__													= ''
					while number <= iterations:
										if number % 3 == 0:
															out += "Fizz"
										if number % 5 == 0:
															out += "Buzz"
										if 0 not in (number % 3, number % 5):
															out += str(UpperCamelCase_		)

										# print(out)
										number += 1
										out += " "
					return out


if __name__ == "__main__":
				import doctest

				doctest.testmod()





