
'''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							(  UpperCAmelCase__							:							List[Any]       ,							UpperCAmelCase__							:							Dict=False):






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


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





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]):
				return unittest.skip('Test was skipped')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]):
				return unittest.skipUnless(_run_slow_tests       ,							'test is slow')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Dict):
				return unittest.skipUnless(not torch.cuda.is_available()       ,							'test requires only a CPU')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Dict):
				return unittest.skipUnless(torch.cuda.is_available()       ,							'test requires a GPU')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]):
				return unittest.skipUnless(is_xpu_available()       ,							'test requires a XPU')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]):
				return unittest.skipUnless(is_mps_available()       ,							'test requires a `mps` backend support in `torch`')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							int):
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()       ,							'test requires the Hugging Face suite')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[Any]):
				return unittest.skipUnless(is_bnb_available()       ,							'test requires the bitsandbytes library')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]):
				return unittest.skipUnless(is_tpu_available()       ,							'test requires TPU')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]):
				return unittest.skipUnless(torch.cuda.device_count() == 1       ,							'test requires a GPU')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]):
				return unittest.skipUnless(torch.xpu.device_count() == 1       ,							'test requires a XPU')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]):
				return unittest.skipUnless(torch.cuda.device_count() > 1       ,							'test requires multiple GPUs')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]):
				return unittest.skipUnless(torch.xpu.device_count() > 1       ,							'test requires multiple XPUs')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[str]):
				return unittest.skipUnless(is_safetensors_available()       ,							'test requires safetensors')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							int):
				return unittest.skipUnless(is_deepspeed_available()       ,							'test requires DeepSpeed')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							str):
				return unittest.skipUnless(is_torch_version('>='       ,							'1.12.0')       ,							'test requires torch version >= 1.12.0')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							str=None       ,							UpperCAmelCase__							:							Tuple=None):






				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							(  UpperCAmelCase__							:							Tuple):
				return unittest.skipUnless(is_tensorboard_available()       ,							'test requires Tensorboard')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Union[str, Any]):
				return unittest.skipUnless(is_wandb_available()       ,							'test requires wandb')(__SCREAMING_SNAKE_CASE)





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]):
				return unittest.skipUnless(is_comet_ml_available()       ,							'test requires comet_ml')(__SCREAMING_SNAKE_CASE)


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





def    UpperCAmelCase							(  UpperCAmelCase__							:							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'       ,							)(__SCREAMING_SNAKE_CASE)




class     a_		(   unittest.TestCase):
					_lowerCAmelCase			     =	True
					@classmethod
					def     UpperCAmelCase_							(     cls      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[Any]									= tempfile.mkdtemp()
					@classmethod
					def     UpperCAmelCase_							(     cls      ):

									"""simple docstring"""


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




					def     UpperCAmelCase_							(     self      ):

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





class     a_		(   unittest.TestCase):
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


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





class     a_		(   unittest.TestCase):
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


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





def    UpperCAmelCase							(  UpperCAmelCase__							:							Dict):
				lowerCamelCase					:			Any									= AcceleratorState()
				lowerCamelCase					:			Optional[int]									= tensor[None].clone().to(state.device)
				lowerCamelCase					:			Any									= gather(__SCREAMING_SNAKE_CASE).cpu()
				lowerCamelCase					:			List[str]									= tensor[0].cpu()
				for i in range(tensors.shape[0]):
								if not torch.equal(tensors[i]       ,							__SCREAMING_SNAKE_CASE):
												return False
				return True




class     a_		:
					def __init__(     self,    A,    A,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[Any]									= returncode
									lowerCamelCase					:			List[Any]									= stdout
									lowerCamelCase					:			Tuple									= stderr





async def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]       ,							UpperCAmelCase__							:							List[Any]):






				while True:
								lowerCamelCase					:			List[str]									= await stream.readline()
								if line:
												callback(__SCREAMING_SNAKE_CASE)
								else:
												break





async def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]       ,							UpperCAmelCase__							:							int=None       ,							UpperCAmelCase__							:							Union[str, Any]=None       ,							UpperCAmelCase__							:							Union[str, Any]=None       ,							UpperCAmelCase__							:							str=False       ,							UpperCAmelCase__							:							Dict=False):






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

				lowerCamelCase					:			List[Any]									= 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)

				lowerCamelCase					:			Any									= []
				lowerCamelCase					:			Any									= []

				def tee(UpperCAmelCase__							:							Union[str, Any]       ,							UpperCAmelCase__							:							str       ,							UpperCAmelCase__							:							Any       ,							UpperCAmelCase__							:							Optional[Any]=""):
								lowerCamelCase					:			int									= 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 UpperCAmelCase__: tee(__SCREAMING_SNAKE_CASE       ,							__SCREAMING_SNAKE_CASE       ,							sys.stdout       ,							label='stdout:'))),
				        asyncio.create_task(_read_stream(p.stderr       ,							lambda UpperCAmelCase__: 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							(  UpperCAmelCase__							:							Dict       ,							UpperCAmelCase__							:							int=None       ,							UpperCAmelCase__							:							Dict=None       ,							UpperCAmelCase__							:							str=1_80       ,							UpperCAmelCase__							:							int=False       ,							UpperCAmelCase__							:							List[Any]=True):
				lowerCamelCase					:			Optional[int]									= asyncio.get_event_loop()
				lowerCamelCase					:			Union[str, Any]									= 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))

				lowerCamelCase					:			Optional[Any]									= " ".join(__SCREAMING_SNAKE_CASE)
				if result.returncode > 0:
								lowerCamelCase					:			List[Any]									= "\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_		(   snake_case__):
					pass





def    UpperCAmelCase							(  UpperCAmelCase__							:							int       ,							UpperCAmelCase__							:							Tuple=False):






				try:
								lowerCamelCase					:			Dict									= subprocess.check_output(__SCREAMING_SNAKE_CASE       ,							stderr=subprocess.STDOUT)
								if return_stdout:
												if hasattr(__SCREAMING_SNAKE_CASE       ,							'decode'):
																lowerCamelCase					:			int									= 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'''






def    UpperCAmelCase							(  UpperCAmelCase__							:							list[int]):
				if not nums:  # Makes sure that the list is not empty
								raise ValueError('List is empty')

				lowerCamelCase					:			int									= sum(UpperCAmelCase__) / len(UpperCAmelCase__)  # Calculate the average
				return sum(abs(x - average) for x in nums) / len(UpperCAmelCase__)


if __name__ == "__main__":
					import doctest

					doctest.testmod()
