



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__	(					lowerCamelCase_	:	Tuple ,lowerCamelCase_	:	Dict=False):





				'''simple docstring'''

				try:
								lowerCAmelCase__  :       Optional[int]				=  os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								lowerCAmelCase__  :       Optional[Any]				=  default
				else:
								# KEY is set, convert it to True or False.
								try:
												lowerCAmelCase__  :       int				=  strtobool(lowerCamelCase_)
								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       :	Any            =parse_flag_from_env('RUN_SLOW', default=False)






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Tuple):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Dict):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	str):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	int):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Any):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Tuple):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Tuple):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	List[str]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Optional[Any]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	str):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Optional[int]):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	int=None ,lowerCamelCase_	:	Tuple=None):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	str):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	int):





				'''simple docstring'''

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Optional[int]):





				'''simple docstring'''

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


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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





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



class  lowerCamelCase__    (							unittest.TestCase):




		'''simple docstring'''



		snake_case_			=True



		@classmethod
		def 	lowerCAmelCase__   (cls				)  ->    List[str]:

						"""simple docstring"""






						lowerCAmelCase__  :       Tuple				=  tempfile.mkdtemp()



		@classmethod
		def 	lowerCAmelCase__   (cls				)  ->    List[str]:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self				)  ->    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(__lowerCamelCase				)



class  lowerCamelCase__    (							unittest.TestCase):




		'''simple docstring'''



		def 	lowerCAmelCase__   (self				)  ->    Dict:

						"""simple docstring"""






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



class  lowerCamelCase__    (							unittest.TestCase):




		'''simple docstring'''



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Tuple:

						"""simple docstring"""






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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Any):





				'''simple docstring'''

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



class  lowerCamelCase__    :




		'''simple docstring'''



		def __init__(self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase				)  ->    List[Any]:

						"""simple docstring"""






						lowerCAmelCase__  :       str				=  returncode
						lowerCAmelCase__  :       List[str]				=  stdout
						lowerCAmelCase__  :       List[Any]				=  stderr






async def 			lowerCAmelCase__	(					lowerCamelCase_	:	Any ,lowerCamelCase_	:	Any):





				'''simple docstring'''

				while True:
								lowerCAmelCase__  :       Union[str, Any]				=  await stream.readline()
								if line:
												callback(lowerCamelCase_)
								else:
												break






async def 			lowerCAmelCase__	(					lowerCamelCase_	:	Any ,lowerCamelCase_	:	Union[str, Any]=None ,lowerCamelCase_	:	Dict=None ,lowerCamelCase_	:	Any=None ,lowerCamelCase_	:	str=False ,lowerCamelCase_	:	List[str]=False):





				'''simple docstring'''

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

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

				# 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__  :       Union[str, Any]				=  []
				lowerCAmelCase__  :       List[str]				=  []

				def tee(lowerCamelCase_	:	int ,lowerCamelCase_	:	List[Any] ,lowerCamelCase_	:	List[Any] ,lowerCamelCase_	:	int=""):
								lowerCAmelCase__  :       Optional[int]				=  line.decode('''utf-8''').rstrip()
								sink.append(lowerCamelCase_)
								if not quiet:
												print(lowerCamelCase_ ,lowerCamelCase_ ,file=lowerCamelCase_)

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






def 			lowerCAmelCase__	(					lowerCamelCase_	:	str ,lowerCamelCase_	:	Optional[Any]=None ,lowerCamelCase_	:	int=None ,lowerCamelCase_	:	str=180 ,lowerCamelCase_	:	Optional[Any]=False ,lowerCamelCase_	:	Optional[int]=True):





				'''simple docstring'''

				lowerCAmelCase__  :       Dict				=  asyncio.get_event_loop()
				lowerCAmelCase__  :       List[Any]				=  loop.run_until_complete(
				    _stream_subprocess(lowerCamelCase_ ,env=lowerCamelCase_ ,stdin=lowerCamelCase_ ,timeout=lowerCamelCase_ ,quiet=lowerCamelCase_ ,echo=lowerCamelCase_))

				lowerCAmelCase__  :       int				=  ''' '''.join(lowerCamelCase_)
				if result.returncode > 0:
								lowerCAmelCase__  :       List[str]				=  '''\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  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		pass






def 			lowerCAmelCase__	(					lowerCamelCase_	:	List[str] ,lowerCamelCase_	:	int=False):





				'''simple docstring'''

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






from __future__ import annotations






def 			lowerCAmelCase__	(					lowerCamelCase_	:	int):





				'''simple docstring'''

				lowerCAmelCase__  :       Optional[int]				=  str(lowerCamelCase_)
				return len(lowerCamelCase_) == 9 and set(lowerCamelCase_) == set('''123456789''')






def 			lowerCAmelCase__	(					):





				'''simple docstring'''

				for base_num in range(9999 ,4999 ,-1):
								lowerCAmelCase__  :       Union[str, Any]				=  100002 * base_num
								if is_9_pandigital(lowerCamelCase_):
												return candidate

				for base_num in range(333 ,99 ,-1):
								lowerCAmelCase__  :       Any				=  1002003 * base_num
								if is_9_pandigital(lowerCamelCase_):
												return candidate

				return None


if __name__ == "__main__":
							print(f"""{solution() = }""")

