





'''simple docstring'''

import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


a   	=    logging.get_logger(__name__)

def     __magic_name__							(				__UpperCAmelCase=None				,						__UpperCAmelCase=None   )    ->       Dict:

   '''simple docstring'''







   return field(default_factory=lambda: default				,						metadata=__UpperCAmelCase   )







@dataclass
class __a			:
   __UpperCamelCase :			List[str]						   =						list_field(
       default=[], metadata={
           'help': (
               'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version'
               ' of all available models'
           )
       }, )

   __UpperCamelCase :			List[int]						   =						list_field(
       default=[8], metadata={'help': 'List of batch sizes for which memory and time performance will be evaluated'}      )

   __UpperCamelCase :			List[int]						   =						list_field(
       default=[8, 32, 128, 512], metadata={'help': 'List of sequence lengths for which memory and time performance will be evaluated'}, )

   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={'help': 'Whether to benchmark inference of model. Inference can be disabled via --no-inference.'}, )
   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={'help': 'Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'}, )
   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={'help': 'Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'}      )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Use FP16 to accelerate inference.'}      )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Benchmark training of model'}      )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Verbose memory tracing'}      )
   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={'help': 'Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'}, )
   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={
           'help': 'Whether to perform memory measurements. Memory measurements can be disabled via --no-memory'
       }, )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Trace memory line by line'}      )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Save result to a CSV file'}      )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Save all print statements in a log file'}      )
   __UpperCamelCase :			bool						   =						field(default=_snake_case, metadata={'help': 'Whether to print environment information'}      )
   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={
           'help': (
               'Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use'
               ' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled'
               ' for debugging / testing and on TPU.'
           )
       }, )
   __UpperCamelCase :			str						   =						field(
       default=F'inference_time_{round(time()      )}.csv', metadata={'help': 'CSV filename used if saving time results to csv.'}, )
   __UpperCamelCase :			str						   =						field(
       default=F'inference_memory_{round(time()      )}.csv', metadata={'help': 'CSV filename used if saving memory results to csv.'}, )
   __UpperCamelCase :			str						   =						field(
       default=F'train_time_{round(time()      )}.csv', metadata={'help': 'CSV filename used if saving time results to csv for training.'}, )
   __UpperCamelCase :			str						   =						field(
       default=F'train_memory_{round(time()      )}.csv', metadata={'help': 'CSV filename used if saving memory results to csv for training.'}, )
   __UpperCamelCase :			str						   =						field(
       default=F'env_info_{round(time()      )}.csv', metadata={'help': 'CSV filename used if saving environment information.'}, )
   __UpperCamelCase :			str						   =						field(
       default=F'log_{round(time()      )}.csv', metadata={'help': 'Log filename used if print statements are saved in log.'}, )
   __UpperCamelCase :			int						   =						field(default=3, metadata={'help': 'Times an experiment will be run.'}      )
   __UpperCamelCase :			bool						   =						field(
       default=_snake_case, metadata={
           'help': (
               'Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain'
               ' model weights.'
           )
       }, )





   def   UpperCAmelCase__  (       self					:      List[Any]     ):

      '''simple docstring'''

      warnings.warn(
          f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils"""
          """ are deprecated in general and it is advised to use external Benchmarking libraries """
          """ to benchmark Transformer models."""					,lowerCamelCase					,)





   def   UpperCAmelCase__  (       self					:      int     ):

      '''simple docstring'''

      return json.dumps(dataclasses.asdict(self     )					,indent=2     )





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      if len(self.models     ) <= 0:
         raise ValueError(
             """Please make sure you provide at least one model name / model identifier, *e.g.* `--models"""
             """ bert-base-cased` or `args.models = ['bert-base-cased']."""     )
      return self.models





   @property
   def   UpperCAmelCase__  (       self					:      Tuple     ):

      '''simple docstring'''

      if not self.multi_process:
         return False
      elif self.is_tpu:
         logger.info("""Multiprocessing is currently not possible on TPU."""     )
         return False
      else:
         return True











'''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       _UpperCamelCase			(_lowerCamelCase				:  List[Any] ,						_lowerCamelCase				:  Tuple=False						)-> Union[str, Any]:




     '''simple docstring'''





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


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

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

# Audio
UpperCAmelCase_							:	str	     =		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_							:	Tuple	     =		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_							:	Union[str, Any]	     =		pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

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







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




     '''simple docstring'''





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







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




     '''simple docstring'''





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







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




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> List[Any]:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  List[str]						)-> List[str]:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[Any]						)-> Dict:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Any:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple						)-> str:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> Any:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Tuple:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> str:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Dict:




     '''simple docstring'''





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

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

     return _require_spacy_model







def       _UpperCamelCase			(_lowerCamelCase				:  str						)-> Dict:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple						)-> str:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Any						)-> int:




     '''simple docstring'''





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







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




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  str						)-> int:




     '''simple docstring'''





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







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




     '''simple docstring'''





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







def       _UpperCamelCase			(*_lowerCamelCase				:  str						)-> Optional[int]:




     '''simple docstring'''





     def decorate(cls				:  Optional[Any]						):
          for name, fn in cls.__dict__.items():
               if callable(_lowerCamelCase						) and name.startswith('''test'''						):
                    for decorator in decorators:
                         __snake_case            =	decorator(_lowerCamelCase						)
                    setattr(cls ,						_lowerCamelCase ,						_lowerCamelCase						)
          return cls

     return decorate





class      lowerCAmelCase (			__lowerCAmelCase):
       pass





class      lowerCAmelCase (			__lowerCAmelCase):
       __lowercase	:   List[str]										=      0
       __lowercase	:   Dict										=      1
       __lowercase	:   List[Any]										=      2







@contextmanager
def       _UpperCamelCase			(_lowerCamelCase				:  Dict=OfflineSimulationMode.CONNECTION_FAILS ,						_lowerCamelCase				:  Optional[int]=1E-16						)-> Tuple:




     '''simple docstring'''





     __snake_case            =	requests.Session().request

     def timeout_request(_lowerCamelCase				:  Any ,						_lowerCamelCase				:  str ,						_lowerCamelCase				:  str ,						**_lowerCamelCase				:  Any						):
          # Change the url to an invalid url so that the connection hangs
          __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.'''						)
          __snake_case            =	timeout
          try:
               return online_request(_lowerCamelCase ,						_lowerCamelCase ,						**_lowerCamelCase						)
          except Exception as e:
               # The following changes in the error are just here to make the offline timeout error prettier
               __snake_case            =	url
               __snake_case            =	e.args[0]
               __snake_case            =	(max_retry_error.args[0].replace('''10.255.255.1''' ,						f'''OfflineMock[{url}]'''						),)
               __snake_case            =	(max_retry_error,)
               raise

     def raise_connection_error(_lowerCamelCase				:  Union[str, Any] ,						_lowerCamelCase				:  Optional[int] ,						**_lowerCamelCase				:  Dict						):
          raise requests.ConnectionError('''Offline mode is enabled.''' ,						request=_lowerCamelCase						)

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







@contextmanager
def       _UpperCamelCase			(*_lowerCamelCase				:  Union[str, Any] ,						**_lowerCamelCase				:  List[str]						)-> Any:




     '''simple docstring'''





     __snake_case            =	str(Path().resolve()						)
     with tempfile.TemporaryDirectory(*_lowerCamelCase ,						**_lowerCamelCase						) as tmp_dir:
          try:
               os.chdir(_lowerCamelCase						)
               yield
          finally:
               os.chdir(_lowerCamelCase						)







@contextmanager
def       _UpperCamelCase			()-> Optional[int]:




     '''simple docstring'''





     import gc

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







@contextmanager
def       _UpperCamelCase			()-> List[Any]:




     '''simple docstring'''





     import gc

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







def       _UpperCamelCase			(_lowerCamelCase				:  Any ,						_lowerCamelCase				:  int						)-> Any:




     '''simple docstring'''





     return deepcopy(_lowerCamelCase						).integers(0 ,						1_00 ,						10						).tolist() == deepcopy(_lowerCamelCase						).integers(0 ,						1_00 ,						10						).tolist()







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




     '''simple docstring'''





     import decorator
     from requests.exceptions import HTTPError

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

     return decorator.decorator(_wrapper ,						_lowerCamelCase						)





class      lowerCAmelCase :


       def __init__( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	returncode
            __snake_case            =	stdout
            __snake_case            =	stderr







async def       _UpperCamelCase			(_lowerCamelCase				:  List[str] ,						_lowerCamelCase				:  Union[str, Any]						)-> Dict:




     '''simple docstring'''





     while True:
          __snake_case            =	await stream.readline()
          if line:
               callback(_lowerCamelCase						)
          else:
               break







async def       _UpperCamelCase			(_lowerCamelCase				:  Tuple ,						_lowerCamelCase				:  Optional[int]=None ,						_lowerCamelCase				:  Optional[Any]=None ,						_lowerCamelCase				:  Tuple=None ,						_lowerCamelCase				:  Dict=False ,						_lowerCamelCase				:  List[Any]=False						)-> _RunOutput:




     '''simple docstring'''





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

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

     __snake_case            =	[]
     __snake_case            =	[]

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







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[Any] ,						_lowerCamelCase				:  Any=None ,						_lowerCamelCase				:  List[str]=None ,						_lowerCamelCase				:  Optional[Any]=1_80 ,						_lowerCamelCase				:  Dict=False ,						_lowerCamelCase				:  int=True						)-> _RunOutput:




     '''simple docstring'''





     __snake_case            =	asyncio.get_event_loop()
     __snake_case            =	loop.run_until_complete(
         _stream_subprocess(_lowerCamelCase ,						env=_lowerCamelCase ,						stdin=_lowerCamelCase ,						timeout=_lowerCamelCase ,						quiet=_lowerCamelCase ,						echo=_lowerCamelCase						)						)

     __snake_case            =	''' '''.join(_lowerCamelCase						)
     if result.returncode > 0:
          __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       _UpperCamelCase			()-> Dict:




     '''simple docstring'''





     __snake_case            =	os.environ.get('''PYTEST_XDIST_WORKER''' ,						'''gw0'''						)
     __snake_case            =	re.sub(R'''^gw''' ,						'''''' ,						_lowerCamelCase ,						0 ,						re.M						)
     return int(_lowerCamelCase						)







def       _UpperCamelCase			()-> Tuple:




     '''simple docstring'''





     __snake_case            =	2_95_00
     __snake_case            =	pytest_xdist_worker_id()
     return port + uniq_delta






