



"""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       _lowerCamelCase				(							UpperCAmelCase_ :       int,	UpperCAmelCase_ :       Tuple=False     )	-> int:






	"""simple docstring"""





	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


UpperCamelCase     =							parse_flag_from_env("""RUN_SLOW""", default=False)

def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[int]     )	-> Tuple:






	"""simple docstring"""





	return unittest.skip("Test was skipped"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[Any]     )	-> List[Any]:






	"""simple docstring"""





	return unittest.skipUnless(_run_slow_tests,	"test is slow"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Tuple     )	-> Optional[int]:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       int     )	-> Any:






	"""simple docstring"""





	return unittest.skipUnless(torch.cuda.is_available(),	"test requires a GPU"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       str     )	-> Tuple:






	"""simple docstring"""





	return unittest.skipUnless(is_xpu_available(),	"test requires a XPU"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[Any]     )	-> Any:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       List[Any]     )	-> str:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[Any]     )	-> List[Any]:






	"""simple docstring"""





	return unittest.skipUnless(is_bnb_available(),	"test requires the bitsandbytes library"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Any     )	-> int:






	"""simple docstring"""





	return unittest.skipUnless(is_tpu_available(),	"test requires TPU"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       int     )	-> str:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       str     )	-> str:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       Any     )	-> Union[str, Any]:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       List[str]     )	-> Optional[int]:






	"""simple docstring"""





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

def       _lowerCamelCase				(							UpperCAmelCase_ :       Tuple     )	-> Any:






	"""simple docstring"""





	return unittest.skipUnless(is_safetensors_available(),	"test requires safetensors"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Tuple     )	-> Union[str, Any]:






	"""simple docstring"""





	return unittest.skipUnless(is_deepspeed_available(),	"test requires DeepSpeed"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       int     )	-> Union[str, Any]:






	"""simple docstring"""





	return unittest.skipUnless(is_torch_version(">=",	"1.12.0"     ),	"test requires torch version >= 1.12.0"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Any=None,	UpperCAmelCase_ :       Any=None     )	-> Union[str, Any]:






	"""simple docstring"""





	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       _lowerCamelCase				(							UpperCAmelCase_ :       Dict     )	-> Optional[Any]:






	"""simple docstring"""





	return unittest.skipUnless(is_tensorboard_available(),	"test requires Tensorboard"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Union[str, Any]     )	-> List[str]:






	"""simple docstring"""





	return unittest.skipUnless(is_wandb_available(),	"test requires wandb"     )(UpperCAmelCase_     )

def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[Any]     )	-> str:






	"""simple docstring"""





	return unittest.skipUnless(is_comet_ml_available(),	"test requires comet_ml"     )(UpperCAmelCase_     )


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

def       _lowerCamelCase				(							UpperCAmelCase_ :       Tuple     )	-> Dict:






	"""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",	)(UpperCAmelCase_     )






class       UpperCamelCase__			(   unittest.TestCase      ):

			"""simple docstring"""


			A__	:					Dict							  =     True


			@classmethod
			def   snake_case__	(      cls		)      ->	Union[str, Any]:
				A__											=					tempfile.mkdtemp()


			@classmethod
			def   snake_case__	(      cls		)      ->	Union[str, Any]:
				if os.path.exists(cls.tmpdir		):
					shutil.rmtree(cls.tmpdir		)







			def   snake_case__	(      self		)      ->	int:
				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   snake_case__	(      self		)      ->	Any:
				super().tearDown()
				# Reset the state of the AcceleratorState singleton.
				AcceleratorState._reset_state()
				PartialState._reset_state()






class       UpperCamelCase__			(   unittest.TestCase      ):

			"""simple docstring"""


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__		)      ->	Optional[Any]:
				A__											=					mocks if isinstance(SCREAMING_SNAKE_CASE__						,	(tuple, list)		) else [mocks]
				for m in self.mocks:
					m.start()
					self.addCleanup(m.stop		)



def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[int]     )	-> Union[str, Any]:






	"""simple docstring"""





	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						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)      ->	List[Any]:
				A__											=					returncode
				A__											=					stdout
				A__											=					stderr



async def       _lowerCamelCase				(							UpperCAmelCase_ :       Dict,	UpperCAmelCase_ :       Dict     )	-> Dict:






	"""simple docstring"""





	while True:
		A__											=					await stream.readline()
		if line:
			callback(UpperCAmelCase_     )
		else:
			break

async def       _lowerCamelCase				(							UpperCAmelCase_ :       List[Any],	UpperCAmelCase_ :       Union[str, Any]=None,	UpperCAmelCase_ :       Dict=None,	UpperCAmelCase_ :       Any=None,	UpperCAmelCase_ :       Union[str, Any]=False,	UpperCAmelCase_ :       List[str]=False     )	-> _RunOutput:






	"""simple docstring"""





	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[Any],	UpperCAmelCase_ :       int,	UpperCAmelCase_ :       Tuple,	UpperCAmelCase_ :       Dict=""     ):
		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       _lowerCamelCase				(							UpperCAmelCase_ :       Dict,	UpperCAmelCase_ :       Tuple=None,	UpperCAmelCase_ :       Any=None,	UpperCAmelCase_ :       Optional[Any]=180,	UpperCAmelCase_ :       Optional[Any]=False,	UpperCAmelCase_ :       Tuple=True     )	-> _RunOutput:






	"""simple docstring"""





	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__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			pass



def       _lowerCamelCase				(							UpperCAmelCase_ :       List[str],	UpperCAmelCase_ :       str=False     )	-> Dict:






	"""simple docstring"""





	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









"""simple docstring"""







import warnings

from ...utils import logging
from .image_processing_deit import DeiTImageProcessor


UpperCamelCase     =							logging.get_logger(__name__)






class       UpperCamelCase__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			def __init__(      self						,	*SCREAMING_SNAKE_CASE__						,	**SCREAMING_SNAKE_CASE__		)      ->	None:
				warnings.warn(
				    "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
				    " use DeiTImageProcessor instead."						,	SCREAMING_SNAKE_CASE__						,	)
				super().__init__(*SCREAMING_SNAKE_CASE__						,	**SCREAMING_SNAKE_CASE__		)




