






"""simple docstring"""




import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
							import importlib_metadata
else:
							import importlib.metadata as importlib_metadata






def 					_lowerCAmelCase(a   :    Dict			,      a   :    int=False  )      ->       Optional[Any]:



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


UpperCAmelCase_       :							int             =				parse_flag_from_env('''RUN_SLOW''', default=False)
UpperCAmelCase_       :							int             =				parse_flag_from_env('''RUN_REMOTE''', default=False)
UpperCAmelCase_       :							str             =				parse_flag_from_env('''RUN_LOCAL''', default=True)
UpperCAmelCase_       :							Union[str, Any]             =				parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
UpperCAmelCase_       :							str             =				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
UpperCAmelCase_       :							str             =				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
UpperCAmelCase_       :							str             =				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
UpperCAmelCase_       :							Optional[Any]             =				pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
UpperCAmelCase_       :							Any             =				pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
UpperCAmelCase_       :							List[Any]             =				pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
UpperCAmelCase_       :							Dict             =				pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)






def 					_lowerCAmelCase(a   :    Optional[int]  )      ->       Optional[Any]:



	try:
		import faiss  # noqa
	except ImportError:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires faiss'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    List[str]  )      ->       str:



	try:
		import regex  # noqa
	except ImportError:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires regex'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    Optional[Any]  )      ->       Dict:



	try:
		import elasticsearch  # noqa
	except ImportError:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires elasticsearch'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    int  )      ->       List[Any]:



	try:
		import sqlalchemy  # noqa
	except ImportError:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires sqlalchemy'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    Optional[Any]  )      ->       str:



	if not config.TORCH_AVAILABLE:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires PyTorch'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    Optional[Any]  )      ->       Optional[Any]:



	if not config.TF_AVAILABLE:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires TensorFlow'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    Any  )      ->       Dict:



	if not config.JAX_AVAILABLE:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires JAX'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    int  )      ->       int:



	if not config.PIL_AVAILABLE:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires Pillow'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    Optional[Any]  )      ->       int:



	try:
		import transformers  # noqa F401
	except ImportError:
		return unittest.skip('''test requires transformers'''  )(A__  )
	else:
		return test_case






def 					_lowerCAmelCase(a   :    Optional[Any]  )      ->       int:



	try:
		import tiktoken  # noqa F401
	except ImportError:
		return unittest.skip('''test requires tiktoken'''  )(A__  )
	else:
		return test_case






def 					_lowerCAmelCase(a   :    int  )      ->       Any:



	try:
		import spacy  # noqa F401
	except ImportError:
		return unittest.skip('''test requires spacy'''  )(A__  )
	else:
		return test_case






def 					_lowerCAmelCase(a   :    str  )      ->       Dict:



	def _require_spacy_model(a   :    int  ):
		try:
			import spacy  # noqa F401

			spacy.load(A__  )
		except ImportError:
			return unittest.skip('''test requires spacy'''  )(A__  )
		except OSError:
			return unittest.skip('''test requires spacy model \'{}\''''.format(A__  )  )(A__  )
		else:
			return test_case

	return _require_spacy_model






def 					_lowerCAmelCase(a   :    Tuple  )      ->       Optional[Any]:



	try:
		import pyspark  # noqa F401
	except ImportError:
		return unittest.skip('''test requires pyspark'''  )(A__  )
	else:
		return test_case






def 					_lowerCAmelCase(a   :    str  )      ->       Any:



	try:
		import joblibspark  # noqa F401
	except ImportError:
		return unittest.skip('''test requires joblibspark'''  )(A__  )
	else:
		return test_case






def 					_lowerCAmelCase(a   :    Optional[int]  )      ->       Dict:



	if not _run_slow_tests or _run_slow_tests == 0:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test is slow'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    str  )      ->       Any:



	if not _run_local_tests or _run_local_tests == 0:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test is local'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    List[str]  )      ->       int:



	if not _run_packaged_tests or _run_packaged_tests == 0:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test is packaged'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(a   :    Optional[int]  )      ->       int:



	if not _run_remote_tests or _run_remote_tests == 0:
		_SCREAMING_SNAKE_CASE						=unittest.skip('''test requires remote'''  )(A__  )
	return test_case






def 					_lowerCAmelCase(*a   :    List[Any]  )      ->       Dict:



	def decorate(cls   :    str  ):
		for name, fn in cls.__dict__.items():
			if callable(A__  ) and name.startswith('''test'''  ):
				for decorator in decorators:
					_SCREAMING_SNAKE_CASE						=decorator(A__  )
				setattr(cls			,      A__			,      A__  )
		return cls

	return decorate


class 	__UpperCAmelCase		(				_lowerCamelCase	):


	'''simple docstring'''





	pass




class 	__UpperCAmelCase		(				_lowerCamelCase	):


	'''simple docstring'''





	lowercase		:	Any							     =				0
	lowercase		:	Optional[int]							     =				1
	lowercase		:	Optional[int]							     =				2






@contextmanager
def 					_lowerCAmelCase(a   :    Union[str, Any]=OfflineSimulationMode.CONNECTION_FAILS			,      a   :    Dict=1E-16  )      ->       List[str]:
	_SCREAMING_SNAKE_CASE						=requests.Session().request

	def timeout_request(a   :    Any			,      a   :    List[str]			,      a   :    Union[str, Any]			,      **a   :    int  ):
		# Change the url to an invalid url so that the connection hangs
		_SCREAMING_SNAKE_CASE						='''https://10.255.255.1'''
		if kwargs.get('''timeout'''  ) is None:
			raise RequestWouldHangIndefinitelyError(
			    f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""  )
		_SCREAMING_SNAKE_CASE						=timeout
		try:
			return online_request(A__			,      A__			,      **A__  )
		except Exception as e:
			# The following changes in the error are just here to make the offline timeout error prettier
			_SCREAMING_SNAKE_CASE						=url
			_SCREAMING_SNAKE_CASE						=e.args[0]
			_SCREAMING_SNAKE_CASE						=(max_retry_error.args[0].replace('''10.255.255.1'''			,      f"""OfflineMock[{url}]"""  ),)
			_SCREAMING_SNAKE_CASE						=(max_retry_error,)
			raise

	def raise_connection_error(a   :    int			,      a   :    Any			,      **a   :    str  ):
		raise requests.ConnectionError('''Offline mode is enabled.'''			,      request=A__  )

	if mode is OfflineSimulationMode.CONNECTION_FAILS:
		with patch('''requests.Session.send'''			,      A__  ):
			yield
	elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
		# inspired from https://stackoverflow.com/a/904609
		with patch('''requests.Session.request'''			,      A__  ):
			yield
	elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
		with patch('''datasets.config.HF_DATASETS_OFFLINE'''			,      A__  ):
			yield
	else:
		raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''  )






@contextmanager
def 					_lowerCAmelCase(*a   :    Any			,      **a   :    Optional[Any]  )      ->       int:
	_SCREAMING_SNAKE_CASE						=str(Path().resolve()  )
	with tempfile.TemporaryDirectory(*A__			,      **A__  ) as tmp_dir:
		try:
			os.chdir(A__  )
			yield
		finally:
			os.chdir(A__  )






@contextmanager
def 					_lowerCAmelCase()      ->       str:
	import gc

	gc.collect()
	_SCREAMING_SNAKE_CASE						=pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."






@contextmanager
def 					_lowerCAmelCase()      ->       str:
	import gc

	gc.collect()
	_SCREAMING_SNAKE_CASE						=pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."






def 					_lowerCAmelCase(a   :    Tuple			,      a   :    int  )      ->       List[Any]:
	return deepcopy(A__  ).integers(0			,      100			,      10  ).tolist() == deepcopy(A__  ).integers(0			,      100			,      10  ).tolist()






def 					_lowerCAmelCase(a   :    Tuple  )      ->       List[str]:
	import decorator
	from requests.exceptions import HTTPError

	def _wrapper(a   :    Tuple			,      *a   :    Optional[int]			,      **a   :    Union[str, Any]  ):
		try:
			return func(*A__			,      **A__  )
		except HTTPError as err:
			if str(A__  ).startswith('''500'''  ) or str(A__  ).startswith('''502'''  ):
				pytest.xfail(str(A__  )  )
			raise err

	return decorator.decorator(_wrapper			,      A__  )


class 	__UpperCAmelCase		:


	'''simple docstring'''





	def __init__(     self      ,      _A      ,      _A      ,      _A					):



		'''simple docstring'''

		_SCREAMING_SNAKE_CASE						=returncode
		_SCREAMING_SNAKE_CASE						=stdout
		_SCREAMING_SNAKE_CASE						=stderr






async def 					_lowerCAmelCase(a   :    int			,      a   :    str  )      ->       Optional[Any]:



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






async def 					_lowerCAmelCase(a   :    List[Any]			,      a   :    int=None			,      a   :    Dict=None			,      a   :    List[Any]=None			,      a   :    List[Any]=False			,      a   :    str=False  )      ->       _RunOutput:



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

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

	_SCREAMING_SNAKE_CASE						=[]
	_SCREAMING_SNAKE_CASE						=[]

	def tee(a   :    Optional[int]			,      a   :    List[Any]			,      a   :    Dict			,      a   :    List[Any]=""  ):
		_SCREAMING_SNAKE_CASE						=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(
	    [
	        _read_stream(p.stdout			,      lambda a  : tee(A__			,      A__			,      sys.stdout			,      label='''stdout:'''  )  ),
	        _read_stream(p.stderr			,      lambda a  : tee(A__			,      A__			,      sys.stderr			,      label='''stderr:'''  )  ),
	    ]			,      timeout=A__			,      )
	return _RunOutput(await p.wait()			,      A__			,      A__  )






def 					_lowerCAmelCase(a   :    Optional[int]			,      a   :    Union[str, Any]=None			,      a   :    Tuple=None			,      a   :    Union[str, Any]=180			,      a   :    str=False			,      a   :    Tuple=True  )      ->       _RunOutput:
	_SCREAMING_SNAKE_CASE						=asyncio.get_event_loop()
	_SCREAMING_SNAKE_CASE						=loop.run_until_complete(
	    _stream_subprocess(A__			,      env=A__			,      stdin=A__			,      timeout=A__			,      quiet=A__			,      echo=A__  )  )

	_SCREAMING_SNAKE_CASE						=''' '''.join(A__  )
	if result.returncode > 0:
		_SCREAMING_SNAKE_CASE						='''\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}"""  )

	# check that the subprocess actually did run and produced some output, should the test rely on
	# the remote side to do the testing
	if not result.stdout and not result.stderr:
		raise RuntimeError(f"""\'{cmd_str}\' produced no output."""  )

	return result






def 					_lowerCAmelCase()      ->       Optional[Any]:
	_SCREAMING_SNAKE_CASE						=os.environ.get('''PYTEST_XDIST_WORKER'''			,      '''gw0'''  )
	_SCREAMING_SNAKE_CASE						=re.sub(R'''^gw'''			,      ''''''			,      A__			,      0			,      re.M  )
	return int(A__  )






def 					_lowerCAmelCase()      ->       Union[str, Any]:
	_SCREAMING_SNAKE_CASE						=2_9500
	_SCREAMING_SNAKE_CASE						=pytest_xdist_worker_id()
	return port + uniq_delta







# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation

import warnings

from .state import AcceleratorState, GradientState


warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler')





class 					__lowerCAmelCase	:




  def __init__(							self				,  lowerCAmelCase				,  lowerCAmelCase				,  lowerCAmelCase = True				,  lowerCAmelCase = False   )    ->					str:
        '''simple docstring'''






        _lowercase      			=scheduler
        _lowercase      			=optimizers if isinstance(lowerCAmelCase				,  (list, tuple)   ) else [optimizers]
        _lowercase      			=split_batches
        _lowercase      			=step_with_optimizer
        _lowercase      			=GradientState()




  def     A__	(							self				,  *lowerCAmelCase				,  **lowerCAmelCase   )    ->					List[Any]:
        '''simple docstring'''






        if not self.step_with_optimizer:
              # No link between scheduler and optimizer -> just step
              self.scheduler.step(*lowerCAmelCase				,  **lowerCAmelCase   )
              return

        # Otherwise, first make sure the optimizer was stepped.
        if not self.gradient_state.sync_gradients:
              if self.gradient_state.adjust_scheduler:
                    self.scheduler._step_count += 1
              return

        for opt in self.optimizers:
              if opt.step_was_skipped:
                    return
        if self.split_batches:
              # Split batches -> the training dataloader batch size is not changed so one step per training step
              self.scheduler.step(*lowerCAmelCase				,  **lowerCAmelCase   )
        else:
              # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
              # num_processes steps per training step
              _lowercase      			=AcceleratorState().num_processes
              for _ in range(lowerCAmelCase   ):
                    # Special case when using OneCycle and `drop_last` was not used
                    if hasattr(self.scheduler				,  'total_steps'   ):
                          if self.scheduler._step_count <= self.scheduler.total_steps:
                                self.scheduler.step(*lowerCAmelCase				,  **lowerCAmelCase   )
                    else:
                          self.scheduler.step(*lowerCAmelCase				,  **lowerCAmelCase   )




  def     A__	(							self   )    ->					str:
        '''simple docstring'''






        return self.scheduler.get_last_lr()




  def     A__	(							self   )    ->					Tuple:
        '''simple docstring'''






        return self.scheduler.state_dict()




  def     A__	(							self				,  lowerCAmelCase   )    ->					str:
        '''simple docstring'''






        self.scheduler.load_state_dict(lowerCAmelCase   )




  def     A__	(							self   )    ->					int:
        '''simple docstring'''






        return self.scheduler.get_lr()




  def     A__	(							self				,  *lowerCAmelCase				,  **lowerCAmelCase   )    ->					Optional[int]:
        '''simple docstring'''






        return self.scheduler.print_lr(*lowerCAmelCase				,  **lowerCAmelCase   )


