






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


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







def      snake_case		(							UpperCAmelCase	:       Dict   ):
				return unittest.skip('Test was skipped'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       int   ):
				return unittest.skipUnless(_run_slow_tests,						'test is slow'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       List[Any]   ):
				return unittest.skipUnless(not torch.cuda.is_available(),						'test requires only a CPU'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Tuple   ):
				return unittest.skipUnless(torch.cuda.is_available(),						'test requires a GPU'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       List[Any]   ):
				return unittest.skipUnless(is_xpu_available(),						'test requires a XPU'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       str   ):
				return unittest.skipUnless(is_mps_available(),						'test requires a `mps` backend support in `torch`'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Union[str, Any]   ):
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available(),						'test requires the Hugging Face suite'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Optional[int]   ):
				return unittest.skipUnless(is_bnb_available(),						'test requires the bitsandbytes library'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       str   ):
				return unittest.skipUnless(is_tpu_available(),						'test requires TPU'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Dict   ):
				return unittest.skipUnless(torch.cuda.device_count() == 1,						'test requires a GPU'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Tuple   ):
				return unittest.skipUnless(torch.xpu.device_count() == 1,						'test requires a XPU'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Union[str, Any]   ):
				return unittest.skipUnless(torch.cuda.device_count() > 1,						'test requires multiple GPUs'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       int   ):
				return unittest.skipUnless(torch.xpu.device_count() > 1,						'test requires multiple XPUs'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       int   ):
				return unittest.skipUnless(is_safetensors_available(),						'test requires safetensors'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Optional[int]   ):
				return unittest.skipUnless(is_deepspeed_available(),						'test requires DeepSpeed'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Dict   ):
				return unittest.skipUnless(is_torch_version('>=',						'1.12.0'   ),						'test requires torch version >= 1.12.0'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Optional[int]=None,						UpperCAmelCase	:       Optional[int]=None   ):
				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      snake_case		(							UpperCAmelCase	:       int   ):
				return unittest.skipUnless(is_tensorboard_available(),						'test requires Tensorboard'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       str   ):
				return unittest.skipUnless(is_wandb_available(),						'test requires wandb'   )(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       str   ):
				return unittest.skipUnless(is_comet_ml_available(),						'test requires comet_ml'   )(UpperCAmelCase   )


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







def      snake_case		(							UpperCAmelCase	:       List[str]   ):
				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      UpperCamelCase (				unittest.TestCase ):







		"""simple docstring"""



		snake_case    =   True
		@classmethod
		def       A(  cls		:       Union[str, Any]		)    ->   Tuple:


						'''simple docstring'''
						A	 =      tempfile.mkdtemp()
		@classmethod
		def       A(  cls		:       List[str]		)    ->   Tuple:


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







		def       A(  self		:       Dict		)    ->   Dict:


						'''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      UpperCamelCase (				unittest.TestCase ):







		"""simple docstring"""



		def       A(  self		:       Dict		)    ->   Any:


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


class      UpperCamelCase (				unittest.TestCase ):







		"""simple docstring"""



		def       A(  self		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       Union[mock.Mock, List[mock.Mock]]		)    ->   int:


						'''simple docstring'''
						A	 =      mocks if isinstance(_SCREAMING_SNAKE_CASE						,(tuple, list)		) else [mocks]
						for m in self.mocks:
										m.start()
										self.addCleanup(m.stop		)







def      snake_case		(							UpperCAmelCase	:       Optional[Any]   ):
				A	 =      AcceleratorState()
				A	 =      tensor[None].clone().to(state.device   )
				A	 =      gather(UpperCAmelCase   ).cpu()
				A	 =      tensor[0].cpu()
				for i in range(tensors.shape[0]   ):
								if not torch.equal(tensors[i],						UpperCAmelCase   ):
												return False
				return True
class      UpperCamelCase :







		"""simple docstring"""



		def __init__(  self		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       Dict						,_SCREAMING_SNAKE_CASE		:       List[str]						,_SCREAMING_SNAKE_CASE		:       Any		)    ->   Tuple:


						'''simple docstring'''
						A	 =      returncode
						A	 =      stdout
						A	 =      stderr







async def      snake_case		(							UpperCAmelCase	:       List[str],						UpperCAmelCase	:       Any   ):
				while True:
								A	 =      await stream.readline()
								if line:
												callback(UpperCAmelCase   )
								else:
												break







async def      snake_case		(							UpperCAmelCase	:       List[str],						UpperCAmelCase	:       List[str]=None,						UpperCAmelCase	:       Union[str, Any]=None,						UpperCAmelCase	:       List[str]=None,						UpperCAmelCase	:       Tuple=False,						UpperCAmelCase	:       int=False   ):
				if echo:
								print('\nRunning: ',						' '.join(UpperCAmelCase   )   )

				A	 =      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)

				A	 =      []
				A	 =      []

				def tee(UpperCAmelCase	:       List[str],						UpperCAmelCase	:       List[str],						UpperCAmelCase	:       Dict,						UpperCAmelCase	:       Any=""   ):
								A	 =      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      snake_case		(							UpperCAmelCase	:       Optional[int],						UpperCAmelCase	:       List[str]=None,						UpperCAmelCase	:       List[Any]=None,						UpperCAmelCase	:       Union[str, Any]=1_80,						UpperCAmelCase	:       List[Any]=False,						UpperCAmelCase	:       Optional[int]=True   ):
				A	 =      asyncio.get_event_loop()
				A	 =      loop.run_until_complete(
				    _stream_subprocess(UpperCAmelCase,						env=UpperCAmelCase,						stdin=UpperCAmelCase,						timeout=UpperCAmelCase,						quiet=UpperCAmelCase,						echo=UpperCAmelCase   )   )

				A	 =      ' '.join(UpperCAmelCase   )
				if result.returncode > 0:
								A	 =      '\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      UpperCamelCase (				snake_case__ ):







		"""simple docstring"""



		pass







def      snake_case		(							UpperCAmelCase	:       List[str],						UpperCAmelCase	:       Dict=False   ):
				try:
								A	 =      subprocess.check_output(UpperCAmelCase,						stderr=subprocess.STDOUT   )
								if return_stdout:
												if hasattr(UpperCAmelCase,						'decode'   ):
																A	 =      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













from collections.abc import Callable
class      UpperCamelCase :







		"""simple docstring"""



		def __init__(  self		:       Tuple						,_SCREAMING_SNAKE_CASE		:       Callable | None = None		)    ->   None:


						'''simple docstring'''
						# Stores actual heap items.
						A	 =      []
						# Stores indexes of each item for supporting updates and deletion.
						A	 =      {}
						# Stores current size of heap.
						A	 =      0
						# Stores function used to evaluate the score of an item on which basis ordering
						# will be done.
						A	 =      key or (lambda _SCREAMING_SNAKE_CASE		: x)
		def       A(  self		:       Tuple						,_SCREAMING_SNAKE_CASE		:       int		)    ->   int | None:


						'''simple docstring'''
						return int((i - 1) / 2		) if i > 0 else None
		def       A(  self		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       int		)    ->   int | None:


						'''simple docstring'''
						A	 =      int(2 * i + 1		)
						return left if 0 < left < self.size else None
		def       A(  self		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       int		)    ->   int | None:


						'''simple docstring'''
						A	 =      int(2 * i + 2		)
						return right if 0 < right < self.size else None
		def       A(  self		:       List[str]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   None:


						'''simple docstring'''
						A ,		A	 =      (
						    self.pos_map[self.arr[j][0]],
						    self.pos_map[self.arr[i][0]],
						)
						# Then swap the items in the list.
						A ,		A	 =      self.arr[j], self.arr[i]
		def       A(  self		:       List[str]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   bool:


						'''simple docstring'''
						return self.arr[i][1] < self.arr[j][1]
		def       A(  self		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   int:


						'''simple docstring'''
						A	 =      self._left(_SCREAMING_SNAKE_CASE		)
						A	 =      self._right(_SCREAMING_SNAKE_CASE		)
						A	 =      i

						if left is not None and not self._cmp(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										A	 =      left
						if right is not None and not self._cmp(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										A	 =      right

						return valid_parent
		def       A(  self		:       Any						,_SCREAMING_SNAKE_CASE		:       int		)    ->   None:


						'''simple docstring'''
						A	 =      self._parent(_SCREAMING_SNAKE_CASE		)
						while parent is not None and not self._cmp(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										self._swap(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)
										A ,		A	 =      parent, self._parent(_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       int		)    ->   None:


						'''simple docstring'''
						A	 =      self._get_valid_parent(_SCREAMING_SNAKE_CASE		)
						while valid_parent != index:
										self._swap(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)
										A ,		A	 =      valid_parent, self._get_valid_parent(_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   None:


						'''simple docstring'''
						if item not in self.pos_map:
										return
						A	 =      self.pos_map[item]
						A	 =      [item, self.key(_SCREAMING_SNAKE_CASE		)]
						# Make sure heap is right in both up and down direction.
						# Ideally only one of them will make any change.
						self._heapify_up(_SCREAMING_SNAKE_CASE		)
						self._heapify_down(_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   None:


						'''simple docstring'''
						if item not in self.pos_map:
										return
						A	 =      self.pos_map[item]
						del self.pos_map[item]
						A	 =      self.arr[self.size - 1]
						A	 =      index
						self.size -= 1
						# Make sure heap is right in both up and down direction. Ideally only one
						# of them will make any change- so no performance loss in calling both.
						if self.size > index:
										self._heapify_up(_SCREAMING_SNAKE_CASE		)
										self._heapify_down(_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   None:


						'''simple docstring'''
						A	 =      len(self.arr		)
						if arr_len == self.size:
										self.arr.append([item, self.key(_SCREAMING_SNAKE_CASE		)]		)
						else:
										A	 =      [item, self.key(_SCREAMING_SNAKE_CASE		)]
						A	 =      self.size
						self.size += 1
						self._heapify_up(self.size - 1		)
		def       A(  self		:       str		)    ->   tuple | None:


						'''simple docstring'''
						return self.arr[0] if self.size else None







		def       A(  self		:       Any		)    ->   tuple | None:


						'''simple docstring'''
						A	 =      self.get_top()
						if top_item_tuple:
										self.delete_item(top_item_tuple[0]		)
						return top_item_tuple







def      snake_case		(							):
				pass


if __name__ == "__main__":
					import doctest

					doctest.testmod()





