


"""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   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=False			)      ->			Dict:
							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


__SCREAMING_SNAKE_CASE							:      int						=      parse_flag_from_env('RUN_SLOW', default=False)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Any:
							return unittest.skip("""Test was skipped"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			int:
							return unittest.skipUnless(_run_slow_tests			,	"""test is slow"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			str:
							return unittest.skipUnless(not torch.cuda.is_available()			,	"""test requires only a CPU"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Union[str, Any]:
							return unittest.skipUnless(torch.cuda.is_available()			,	"""test requires a GPU"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Optional[Any]:
							return unittest.skipUnless(is_xpu_available()			,	"""test requires a XPU"""			)(snake_case_			)







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







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			List[Any]:
							return unittest.skipUnless(
							    is_transformers_available() and is_datasets_available()			,	"""test requires the Hugging Face suite"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Optional[int]:
							return unittest.skipUnless(is_bnb_available()			,	"""test requires the bitsandbytes library"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Optional[Any]:
							return unittest.skipUnless(is_tpu_available()			,	"""test requires TPU"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Dict:
							return unittest.skipUnless(torch.cuda.device_count() == 1			,	"""test requires a GPU"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			List[str]:
							return unittest.skipUnless(torch.xpu.device_count() == 1			,	"""test requires a XPU"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Dict:
							return unittest.skipUnless(torch.cuda.device_count() > 1			,	"""test requires multiple GPUs"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			List[str]:
							return unittest.skipUnless(torch.xpu.device_count() > 1			,	"""test requires multiple XPUs"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			List[str]:
							return unittest.skipUnless(is_safetensors_available()			,	"""test requires safetensors"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			str:
							return unittest.skipUnless(is_deepspeed_available()			,	"""test requires DeepSpeed"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Dict:
							return unittest.skipUnless(is_torch_version(""">="""			,	"""1.12.0"""			)			,	"""test requires torch version >= 1.12.0"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=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   _a			( _SCREAMING_SNAKE_CASE			)      ->			Optional[Any]:
							return unittest.skipUnless(is_tensorboard_available()			,	"""test requires Tensorboard"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			int:
							return unittest.skipUnless(is_wandb_available()			,	"""test requires wandb"""			)(snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Optional[int]:
							return unittest.skipUnless(is_comet_ml_available()			,	"""test requires comet_ml"""			)(snake_case_			)


__SCREAMING_SNAKE_CASE							:      int						=      (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Union[str, Any]:
							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        __A       (unittest.TestCase):





							'''simple docstring'''

							__lowercase:						Optional[Any]							 =      True



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



														"""simple docstring"""



														snake_case_          =						tempfile.mkdtemp()



							@classmethod
							def 						lowerCAmelCase    (			cls							: str    )   ->Tuple:



														"""simple docstring"""



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



							def 						lowerCAmelCase    (			self							: Tuple    )   ->List[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(SCREAMING_SNAKE_CASE_    )





class        __A       (unittest.TestCase):





							'''simple docstring'''

							def 						lowerCAmelCase    (			self							: str    )   ->Dict:



														"""simple docstring"""



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





class        __A       (unittest.TestCase):





							'''simple docstring'''

							def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Union[str, Any]    )   ->Union[str, Any]:



														"""simple docstring"""



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







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			str:
							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        __A       :





							'''simple docstring'''

							def __init__(			self							: Dict						,    UpperCAmelCase_							: List[Any]						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: Optional[Any]    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						returncode
														snake_case_          =						stdout
														snake_case_          =						stderr







async def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)      ->			List[str]:
							while True:
														snake_case_          =						await stream.readline()
														if line:
																					callback(snake_case_			)
														else:
																					break







async def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=False			,	_SCREAMING_SNAKE_CASE=False			)      ->			int:
							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(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=""			):
														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 _SCREAMING_SNAKE_CASE			: tee(snake_case_			,	snake_case_			,	sys.stdout			,	label="""stdout:"""			)			)			),
							        asyncio.create_task(_read_stream(p.stderr			,	lambda _SCREAMING_SNAKE_CASE			: tee(snake_case_			,	snake_case_			,	sys.stderr			,	label="""stderr:"""			)			)			),
							    ]			,	timeout=snake_case_			,	)
							return _RunOutput(await p.wait()			,	snake_case_			,	snake_case_			)







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=180			,	_SCREAMING_SNAKE_CASE=False			,	_SCREAMING_SNAKE_CASE=True			)      ->			Union[str, Any]:
							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        __A       (_UpperCAmelCase):





							'''simple docstring'''

							pass







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=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







"""simple docstring"""
def   _a			( _SCREAMING_SNAKE_CASE			)      ->			int:
							assert column_title.isupper()
							snake_case_          =						0
							snake_case_          =						len(_SCREAMING_SNAKE_CASE			) - 1
							snake_case_          =						0

							while index >= 0:
														snake_case_          =						(ord(column_title[index]			) - 64) * pow(26			,	_SCREAMING_SNAKE_CASE			)
														answer += value
														power += 1
														index -= 1

							return answer


if __name__ == "__main__":
				from doctest import testmod

				testmod()



