



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


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


def A						(       __UpperCamelCase					)						->      Any:
			return unittest.skip('Test was skipped'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      str:
			return unittest.skipUnless(_run_slow_tests ,	'test is slow'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Optional[int]:
			return unittest.skipUnless(not torch.cuda.is_available() ,	'test requires only a CPU'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Optional[int]:
			return unittest.skipUnless(torch.cuda.is_available() ,	'test requires a GPU'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      List[Any]:
			return unittest.skipUnless(is_xpu_available() ,	'test requires a XPU'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Tuple:
			return unittest.skipUnless(is_mps_available() ,	'test requires a `mps` backend support in `torch`'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Optional[int]:
			return unittest.skipUnless(
			    is_transformers_available() and is_datasets_available() ,	'test requires the Hugging Face suite'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Any:
			return unittest.skipUnless(is_bnb_available() ,	'test requires the bitsandbytes library'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      int:
			return unittest.skipUnless(is_tpu_available() ,	'test requires TPU'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      List[Any]:
			return unittest.skipUnless(torch.cuda.device_count() == 1 ,	'test requires a GPU'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      int:
			return unittest.skipUnless(torch.xpu.device_count() == 1 ,	'test requires a XPU'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      List[Any]:
			return unittest.skipUnless(torch.cuda.device_count() > 1 ,	'test requires multiple GPUs'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Any:
			return unittest.skipUnless(torch.xpu.device_count() > 1 ,	'test requires multiple XPUs'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      int:
			return unittest.skipUnless(is_safetensors_available() ,	'test requires safetensors'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Any:
			return unittest.skipUnless(is_deepspeed_available() ,	'test requires DeepSpeed'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      Optional[Any]:
			return unittest.skipUnless(is_torch_version('>=' ,	'1.12.0'					) ,	'test requires torch version >= 1.12.0'					)(__lowerCAmelCase					)


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


def A						(       __UpperCamelCase					)						->      List[str]:
			return unittest.skipUnless(is_wandb_available() ,	'test requires wandb'					)(__lowerCAmelCase					)


def A						(       __UpperCamelCase					)						->      List[Any]:
			return unittest.skipUnless(is_comet_ml_available() ,	'test requires comet_ml'					)(__lowerCAmelCase					)


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


def A						(       __UpperCamelCase					)						->      Union[str, Any]:
			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"""






					A__				:		Union[str, Any]			       =    True



					@classmethod
					def     _a							(     cls					:       int					):






								"""simple docstring"""


								A__       =    tempfile.mkdtemp()



					@classmethod
					def     _a							(     cls					:       Any					):






								"""simple docstring"""


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



					def     _a							(     self					:       Optional[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(_a					)







class      __lowerCAmelCase     (		unittest.TestCase      ):
					"""simple docstring"""






					def     _a							(     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     _a							(     self					:       Union[str, Any]				,					_snake_case					:       Any					):






								"""simple docstring"""


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







def A						(       __UpperCamelCase					)						->      List[str]:
			A__       =    AcceleratorState()
			A__       =    tensor[None].clone().to(state.device					)
			A__       =    gather(__lowerCAmelCase					).cpu()
			A__       =    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					:       Tuple				,					_snake_case					:       List[Any]				,					_snake_case					:       int				,					_snake_case					:       Tuple					):






								"""simple docstring"""


								A__       =    returncode
								A__       =    stdout
								A__       =    stderr







async def A						(       __UpperCamelCase ,	__UpperCamelCase					)						->      str:
			while True:
						A__       =    await stream.readline()
						if line:
									callback(__lowerCAmelCase					)
						else:
									break


async def A						(       __UpperCamelCase ,	__UpperCamelCase=None ,	__UpperCamelCase=None ,	__UpperCamelCase=None ,	__UpperCamelCase=False ,	__UpperCamelCase=False					)						->      _RunOutput:
			if echo:
						print('\nRunning: ' ,	' '.join(__lowerCAmelCase					)					)

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

			A__       =    []
			A__       =    []

			def tee(__UpperCamelCase ,	__UpperCamelCase ,	__UpperCamelCase ,	__UpperCamelCase=""					):
						A__       =    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 __UpperCamelCase					: tee(__lowerCAmelCase ,	__lowerCAmelCase ,	sys.stdout ,	label='stdout:'					)					)					),
			        asyncio.create_task(_read_stream(p.stderr ,	lambda __UpperCamelCase					: tee(__lowerCAmelCase ,	__lowerCAmelCase ,	sys.stderr ,	label='stderr:'					)					)					),
			    ] ,	timeout=__lowerCAmelCase ,	)
			return _RunOutput(await p.wait() ,	__lowerCAmelCase ,	__lowerCAmelCase					)


def A						(       __UpperCamelCase ,	__UpperCamelCase=None ,	__UpperCamelCase=None ,	__UpperCamelCase=180 ,	__UpperCamelCase=False ,	__UpperCamelCase=True					)						->      _RunOutput:
			A__       =    asyncio.get_event_loop()
			A__       =    loop.run_until_complete(
			    _stream_subprocess(__lowerCAmelCase ,	env=__lowerCAmelCase ,	stdin=__lowerCAmelCase ,	timeout=__lowerCAmelCase ,	quiet=__lowerCAmelCase ,	echo=__lowerCAmelCase					)					)

			A__       =    """ """.join(__lowerCAmelCase					)
			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      __lowerCAmelCase     (		UpperCamelCase_      ):
					"""simple docstring"""






					pass







def A						(       __UpperCamelCase ,	__UpperCamelCase=False					)						->      str:
			try:
						A__       =    subprocess.check_output(__lowerCAmelCase ,	stderr=subprocess.STDOUT					)
						if return_stdout:
									if hasattr(__lowerCAmelCase ,	'decode'					):
												A__       =    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









import pytest

import datasets


# Import fixture modules as plugins
SCREAMING_SNAKE_CASE__       =      ['''tests.fixtures.files''', '''tests.fixtures.hub''', '''tests.fixtures.fsspec''']


def A						(       __UpperCamelCase ,	__UpperCamelCase					)						->      Optional[int]:
			# Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit")
			for item in items:
						if any(marker in item.keywords for marker in ['integration', 'unit']					):
									continue
						item.add_marker(pytest.mark.unit					)


def A						(       __UpperCamelCase					)						->      str:
			config.addinivalue_line('markers' ,	'torchaudio_latest: mark test to run with torchaudio>=0.12'					)


@pytest.fixture(autouse=__UpperCamelCase					)
def A						(       __UpperCamelCase ,	__UpperCamelCase					)						->      Union[str, Any]:
			# test_hf_cache_home = tmp_path_factory.mktemp("cache")  # TODO: why a cache dir per test function does not work?
			A__       =    tmp_path_factory.getbasetemp() / 'cache'
			A__       =    test_hf_cache_home / 'datasets'
			A__       =    test_hf_cache_home / 'metrics'
			A__       =    test_hf_cache_home / 'modules'
			monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' ,	str(__UpperCamelCase					)					)
			monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' ,	str(__UpperCamelCase					)					)
			monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' ,	str(__UpperCamelCase					)					)
			A__       =    test_hf_datasets_cache / 'downloads'
			monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' ,	str(__UpperCamelCase					)					)
			A__       =    test_hf_datasets_cache / 'downloads' / 'extracted'
			monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' ,	str(__UpperCamelCase					)					)


@pytest.fixture(autouse=__UpperCamelCase ,	scope='session'					)
def A						(       )						->      Union[str, Any]:
			datasets.disable_progress_bar()


@pytest.fixture(autouse=__UpperCamelCase					)
def A						(       __UpperCamelCase					)						->      int:
			# don't take tests into account when counting downloads
			monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' ,	__UpperCamelCase					)






@pytest.fixture
def A						(       __UpperCamelCase					)						->      Any:
			# Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0
			# To be removed once SQLAlchemy 2.0 supported
			monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' ,	__UpperCamelCase					)




