




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__   (		__A:	List[Any]							,__A:	List[Any]=False				):





					'''simple docstring'''






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


__lowerCamelCase   :						Any				=			parse_flag_from_env('''RUN_SLOW''', default=False)







def 		lowercase__   (		__A:	List[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Any				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Optional[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Any				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Dict				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Union[str, Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	str				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Dict				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Optional[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	int				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Optional[int]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	List[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	List[str]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	List[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	int				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	List[str]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Any=None							,__A:	str=None				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Optional[Any]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Optional[int]				):





					'''simple docstring'''






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







def 		lowercase__   (		__A:	Dict				):





					'''simple docstring'''






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


__lowerCamelCase   :						Union[str, Any]				=			(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)







def 		lowercase__   (		__A:	str				):





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


class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			UpperCamelCase__								=True

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   Dict  )						->   Tuple:
								__magic_name__							:	Optional[int]    							=							tempfile.mkdtemp()

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


			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   List[Any]:
								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 							UpperCAmelCase__       ( self			:   List[Any]  )						->   List[Any]:
								super().tearDown()
								# Reset the state of the AcceleratorState singleton.
								AcceleratorState._reset_state()
								PartialState._reset_state()






class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			def 							UpperCAmelCase__       ( self			:   Union[str, Any]       ,						lowerCamelCase_			:   Union[mock.Mock, List[mock.Mock]]  )						->   Optional[int]:
								__magic_name__							:	int    							=							mocks if isinstance(lowerCamelCase_       ,						(tuple, list)  ) else [mocks]
								for m in self.mocks:
													m.start()
													self.addCleanup(m.stop  )







def 		lowercase__   (		__A:	Optional[int]				):





					'''simple docstring'''






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


class    lowerCamelCase    :






			'''simple docstring'''





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







async def 		lowercase__   (		__A:	Optional[int]							,__A:	Optional[int]				):





					'''simple docstring'''






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







async def 		lowercase__   (		__A:	Any							,__A:	List[str]=None							,__A:	int=None							,__A:	str=None							,__A:	Optional[Any]=False							,__A:	Tuple=False				):





					'''simple docstring'''






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

					__magic_name__							:	List[str]    							=							await asyncio.create_subprocess_exec(
					    cmd[0]							,*cmd[1:]							,stdin=__A							,stdout=asyncio.subprocess.PIPE							,stderr=asyncio.subprocess.PIPE							,env=__A							,)

					# 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)

					__magic_name__							:	List[Any]    							=							[]
					__magic_name__							:	Optional[int]    							=							[]

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

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







def 		lowercase__   (		__A:	Any							,__A:	List[str]=None							,__A:	Optional[int]=None							,__A:	Union[str, Any]=1_8_0							,__A:	int=False							,__A:	Tuple=True				):





					'''simple docstring'''






					__magic_name__							:	str    							=							asyncio.get_event_loop()
					__magic_name__							:	int    							=							loop.run_until_complete(
					    _stream_subprocess(__A							,env=__A							,stdin=__A							,timeout=__A							,quiet=__A							,echo=__A				)				)

					__magic_name__							:	int    							=							''' '''.join(__A				)
					if result.returncode > 0:
										__magic_name__							:	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 		lowercase__   (		__A:	List[str]							,__A:	List[Any]=False				):





					'''simple docstring'''






					try:
										__magic_name__							:	int    							=							subprocess.check_output(__A							,stderr=subprocess.STDOUT				)
										if return_stdout:
															if hasattr(__A							,'''decode'''				):
																				__magic_name__							:	List[str]    							=							output.decode('''utf-8'''				)
															return output
					except subprocess.CalledProcessError as e:
										raise SubprocessCallException(
										    F'''Command `{' '.join(__A				)}` failed with the following error:\n\n{e.output.decode()}'''				) from e









import inspect
import os
import unittest
from pathlib import Path

import torch

import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command


class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			UpperCamelCase__								=inspect.getfile(accelerate.test_utils						)
			UpperCamelCase__								=os.path.sep.join(mod_file.split(os.path.sep						)[:-1] + ['''scripts''', '''test_cli.py''']						)

			UpperCamelCase__								=['''accelerate''', '''launch''']
			UpperCamelCase__								=Path.home() / '''.cache/huggingface/accelerate'''
			UpperCamelCase__								='''default_config.yaml'''
			UpperCamelCase__								=config_folder / config_file
			UpperCamelCase__								=config_folder / '''_default_config.yaml'''

			UpperCamelCase__								=Path('''tests/test_configs'''						)

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   Optional[int]  )						->   int:
								if cls.config_path.is_file():
													cls.config_path.rename(cls.changed_path  )

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   Dict  )						->   List[str]:
								if cls.changed_path.is_file():
													cls.changed_path.rename(cls.config_path  )

			def 							UpperCAmelCase__       ( self			:   str  )						->   Optional[Any]:
								__magic_name__							:	Dict    							=							self.base_cmd
								if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
													cmd += ["--multi_gpu"]
								execute_subprocess_async(cmd + [self.test_file_path]       ,						env=os.environ.copy()  )

			def 							UpperCAmelCase__       ( self			:   int  )						->   Optional[int]:
								for config in sorted(self.test_config_path.glob('''**/*.yaml'''  )  ):
													with self.subTest(config_file=lowerCamelCase_  ):
																		execute_subprocess_async(
																		    self.base_cmd + ['''--config_file''', str(lowerCamelCase_  ), self.test_file_path]       ,						env=os.environ.copy()  )


			def 							UpperCAmelCase__       ( self			:   int  )						->   Union[str, Any]:
								execute_subprocess_async(['''accelerate''', '''test''']       ,						env=os.environ.copy()  )






class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			UpperCamelCase__								='''test-tpu'''
			UpperCamelCase__								='''us-central1-a'''
			UpperCamelCase__								='''ls'''
			UpperCamelCase__								=['''accelerate''', '''tpu-config''']
			UpperCamelCase__								='''cd /usr/share'''
			UpperCamelCase__								='''tests/test_samples/test_command_file.sh'''
			UpperCamelCase__								='''Running gcloud compute tpus tpu-vm ssh'''

			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Optional[Any]:
								__magic_name__							:	str    							=							run_command(
								    self.cmd
								    + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   int:
								__magic_name__							:	int    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/0_12_0.yaml''',
								        '''--command''',
								        self.command,
								        '''--tpu_zone''',
								        self.tpu_zone,
								        '''--tpu_name''',
								        self.tpu_name,
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   Tuple:
								__magic_name__							:	Any    							=							run_command(
								    self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug''']       ,						return_stdout=lowerCamelCase_  )
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   Tuple:
								__magic_name__							:	Tuple    							=							run_command(
								    self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   Dict:
								__magic_name__							:	str    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/latest.yaml''',
								        '''--command''',
								        self.command,
								        '''--command''',
								        '''echo "Hello World"''',
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Optional[int]:
								__magic_name__							:	Union[str, Any]    							=							run_command(
								    self.cmd
								    + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   int  )						->   List[Any]:
								__magic_name__							:	List[Any]    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/0_12_0.yaml''',
								        '''--command_file''',
								        self.command_file,
								        '''--tpu_zone''',
								        self.tpu_zone,
								        '''--tpu_name''',
								        self.tpu_name,
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   str  )						->   Dict:
								__magic_name__							:	Tuple    							=							run_command(
								    self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)


			def 							UpperCAmelCase__       ( self			:   Any  )						->   Tuple:
								__magic_name__							:	Tuple    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/latest.yaml''',
								        '''--install_accelerate''',
								        '''--accelerate_version''',
								        '''12.0.0''',
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)



