






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


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





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skip('Test was skipped'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(_run_slow_tests,						'test is slow'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(not torch.cuda.is_available(),						'test requires only a CPU'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(torch.cuda.is_available(),						'test requires a GPU'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_xpu_available(),						'test requires a XPU'       )(lowerCamelCase       )





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





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available(),						'test requires the Hugging Face suite'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_bnb_available(),						'test requires the bitsandbytes library'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_tpu_available(),						'test requires TPU'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(torch.cuda.device_count() == 1,						'test requires a GPU'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(torch.xpu.device_count() == 1,						'test requires a XPU'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(torch.cuda.device_count() > 1,						'test requires multiple GPUs'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(torch.xpu.device_count() > 1,						'test requires multiple XPUs'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_safetensors_available(),						'test requires safetensors'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_deepspeed_available(),						'test requires DeepSpeed'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_torch_version('>=',						'1.12.0'       ),						'test requires torch version >= 1.12.0'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase=None,						lowerCamelCase=None       ):
				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 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_tensorboard_available(),						'test requires Tensorboard'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_wandb_available(),						'test requires wandb'       )(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				return unittest.skipUnless(is_comet_ml_available(),						'test requires comet_ml'       )(lowerCamelCase       )


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





def 				lowercase__		(					lowerCamelCase       ):
				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       ):
						SCREAMING_SNAKE_CASE_:					Optional[int] 					=				True







						@classmethod
						def 			A      (    cls							)		->							List[Any]:
										_SCREAMING_SNAKE_CASE   :		Dict       		=    tempfile.mkdtemp()







						@classmethod
						def 			A      (    cls							)		->							Tuple:
										if os.path.exists(cls.tmpdir							):
														shutil.rmtree(cls.tmpdir							)







						def 			A      (    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(lowerCAmelCase_							)







class _lowerCAmelCase						(    unittest.TestCase       ):







						def 			A      (    self							)		->							Union[str, Any]:
										super().tearDown()
										# Reset the state of the AcceleratorState singleton.
										AcceleratorState._reset_state()
										PartialState._reset_state()







class _lowerCAmelCase						(    unittest.TestCase       ):







						def 			A      (    self   ,				lowerCAmelCase_							)		->							Optional[Any]:
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    mocks if isinstance(lowerCAmelCase_   ,				(tuple, list)							) else [mocks]
										for m in self.mocks:
														m.start()
														self.addCleanup(m.stop							)







def 				lowercase__		(					lowerCamelCase       ):
				_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    AcceleratorState()
				_SCREAMING_SNAKE_CASE   :		Any       		=    tensor[None].clone().to(state.device       )
				_SCREAMING_SNAKE_CASE   :		List[str]       		=    gather(lowerCamelCase       ).cpu()
				_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    tensor[0].cpu()
				for i in range(tensors.shape[0]       ):
								if not torch.equal(tensors[i],						lowerCamelCase       ):
												return False
				return True


class _lowerCAmelCase						:







						def __init__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							str:
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    returncode
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    stdout
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    stderr







async def 				lowercase__		(					lowerCamelCase,						lowerCamelCase       ):
				while True:
								_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    await stream.readline()
								if line:
												callback(lowerCamelCase       )
								else:
												break





async def 				lowercase__		(					lowerCamelCase,						lowerCamelCase=None,						lowerCamelCase=None,						lowerCamelCase=None,						lowerCamelCase=False,						lowerCamelCase=False       ):
				if echo:
								print('\nRunning: ',						' '.join(lowerCamelCase       )       )

				_SCREAMING_SNAKE_CASE   :		List[str]       		=    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)

				_SCREAMING_SNAKE_CASE   :		Tuple       		=    []
				_SCREAMING_SNAKE_CASE   :		Dict       		=    []

				def tee(lowerCamelCase,						lowerCamelCase,						lowerCamelCase,						lowerCamelCase=""       ):
								_SCREAMING_SNAKE_CASE   :		List[str]       		=    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 				lowercase__		(					lowerCamelCase,						lowerCamelCase=None,						lowerCamelCase=None,						lowerCamelCase=180,						lowerCamelCase=False,						lowerCamelCase=True       ):
				_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    asyncio.get_event_loop()
				_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    loop.run_until_complete(
				    _stream_subprocess(lowerCamelCase,						env=lowerCamelCase,						stdin=lowerCamelCase,						timeout=lowerCamelCase,						quiet=lowerCamelCase,						echo=lowerCamelCase       )       )

				_SCREAMING_SNAKE_CASE   :		int       		=    ' '.join(lowerCamelCase       )
				if result.returncode > 0:
								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    '\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						(    __UpperCAmelCase       ):
						pass







def 				lowercase__		(					lowerCamelCase,						lowerCamelCase=False       ):
				try:
								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    subprocess.check_output(lowerCamelCase,						stderr=subprocess.STDOUT       )
								if return_stdout:
												if hasattr(lowerCamelCase,						'decode'       ):
																_SCREAMING_SNAKE_CASE   :		Dict       		=    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









"""simple docstring"""
import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


lowerCAmelCase__    						=			threading.Lock()
lowerCAmelCase__    						=			None

lowerCAmelCase__    						=			{
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

lowerCAmelCase__    						=			logging.WARNING

lowerCAmelCase__    						=			True





def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		int       		=    os.getenv('TRANSFORMERS_VERBOSITY',						lowerCamelCase       )
				if env_level_str:
								if env_level_str in log_levels:
												return log_levels[env_level_str]
								else:
												logging.getLogger().warning(
												    f"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """
												    f"""has to be one of: { ", ".join(log_levels.keys()       ) }"""       )
				return _default_log_level





def 				lowercase__		(					):
				return __name__.split('.'       )[0]





def 				lowercase__		(					):
				return logging.getLogger(_get_library_name()       )





def 				lowercase__		(					):
				global _default_handler

				with _lock:
								if _default_handler:
												# This library has already configured the library root logger.
												return
								_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    logging.StreamHandler()  # Set sys.stderr as stream.
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    sys.stderr.flush

								# Apply our default configuration to the library root logger.
								_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    _get_library_root_logger()
								library_root_logger.addHandler(_default_handler       )
								library_root_logger.setLevel(_get_default_logging_level()       )
								_SCREAMING_SNAKE_CASE   :		int       		=    False





def 				lowercase__		(					):
				global _default_handler

				with _lock:
								if not _default_handler:
												return

								_SCREAMING_SNAKE_CASE   :		Any       		=    _get_library_root_logger()
								library_root_logger.removeHandler(_default_handler       )
								library_root_logger.setLevel(logging.NOTSET       )
								_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    None





def 				lowercase__		(					):
				return log_levels





def 				lowercase__		(					lowerCamelCase = None       ):

				if name is None:
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    _get_library_name()

				_configure_library_root_logger()
				return logging.getLogger(lowerCamelCase       )





def 				lowercase__		(					):
				_configure_library_root_logger()
				return _get_library_root_logger().getEffectiveLevel()





def 				lowercase__		(					lowerCamelCase       ):
				_configure_library_root_logger()
				_get_library_root_logger().setLevel(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				_configure_library_root_logger()

				assert _default_handler is not None
				_get_library_root_logger().removeHandler(_default_handler       )





def 				lowercase__		(					):
				_configure_library_root_logger()

				assert _default_handler is not None
				_get_library_root_logger().addHandler(_default_handler       )





def 				lowercase__		(					lowerCamelCase       ):
				_configure_library_root_logger()

				assert handler is not None
				_get_library_root_logger().addHandler(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				_configure_library_root_logger()

				assert handler is not None and handler not in _get_library_root_logger().handlers
				_get_library_root_logger().removeHandler(lowerCamelCase       )





def 				lowercase__		(					):
				_configure_library_root_logger()
				_SCREAMING_SNAKE_CASE   :		List[str]       		=    False





def 				lowercase__		(					):
				_configure_library_root_logger()
				_SCREAMING_SNAKE_CASE   :		int       		=    True





def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		Any       		=    _get_library_root_logger().handlers

				for handler in handlers:
								_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'       )
								handler.setFormatter(lowerCamelCase       )





def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		List[str]       		=    _get_library_root_logger().handlers

				for handler in handlers:
								handler.setFormatter(lowerCamelCase       )





def 				lowercase__		(					self,						*lowerCamelCase,						**lowerCamelCase       ):
				_SCREAMING_SNAKE_CASE   :		str       		=    os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS',						lowerCamelCase       )
				if no_advisory_warnings:
								return
				self.warning(*lowerCamelCase,						**lowerCamelCase       )


lowerCAmelCase__    						=			warning_advice





@functools.lru_cache(lowerCamelCase       )
def 				lowercase__		(					self,						*lowerCamelCase,						**lowerCamelCase       ):
				self.warning(*lowerCamelCase,						**lowerCamelCase       )


lowerCAmelCase__    						=			warning_once


class _lowerCAmelCase						:







						def __init__(    self   ,				*lowerCAmelCase_   ,				**lowerCAmelCase_							)		->							Optional[int]:  # pylint: disable=unused-argument
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    args[0] if args else None







						def __iter__(    self							)		->							Dict:
										return iter(self._iterator							)







						def __getattr__(    self   ,				lowerCAmelCase_							)		->							Tuple:

										def empty_fn(*lowerCAmelCase_   ,				**lowerCAmelCase_							):  # pylint: disable=unused-argument
														return

										return empty_fn







						def __enter__(    self							)		->							List[Any]:
										return self







						def __exit__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							Optional[Any]:
										return







class _lowerCAmelCase						:







						def __call__(    self   ,				*lowerCAmelCase_   ,				**lowerCAmelCase_							)		->							Optional[Any]:
										if _tqdm_active:
														return tqdm_lib.tqdm(*lowerCAmelCase_   ,				**lowerCAmelCase_							)
										else:
														return EmptyTqdm(*lowerCAmelCase_   ,				**lowerCAmelCase_							)







						def 			A      (    self   ,				*lowerCAmelCase_   ,				**lowerCAmelCase_							)		->							List[str]:
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    None
										if _tqdm_active:
														return tqdm_lib.tqdm.set_lock(*lowerCAmelCase_   ,				**lowerCAmelCase_							)







						def 			A      (    self							)		->							Any:
										if _tqdm_active:
														return tqdm_lib.tqdm.get_lock()







lowerCAmelCase__    						=			_tqdm_cls()





def 				lowercase__		(					):
				global _tqdm_active
				return bool(_tqdm_active       )





def 				lowercase__		(					):
				global _tqdm_active
				_SCREAMING_SNAKE_CASE   :		int       		=    True
				hf_hub_utils.enable_progress_bars()






def 				lowercase__		(					):
				global _tqdm_active
				_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    False
				hf_hub_utils.disable_progress_bars()

