





'''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 						__a(SCREAMING_SNAKE_CASE_	:       Any		,							SCREAMING_SNAKE_CASE_	:       Tuple=False     ):



    '''simple docstring'''





    try:
        _lowerCAmelCase						      =   os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        _lowerCAmelCase						      =   default
    else:
        # KEY is set, convert it to True or False.
        try:
            _lowerCAmelCase						      =   strtobool(SCREAMING_SNAKE_CASE_     )
        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)
_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_REMOTE", default=False)
_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_LOCAL", default=True)
_SCREAMING_SNAKE_CASE									=				parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
_SCREAMING_SNAKE_CASE									=				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
_SCREAMING_SNAKE_CASE									=				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
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
_SCREAMING_SNAKE_CASE									=				pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)


def 						__a(SCREAMING_SNAKE_CASE_	:       str     ):



    '''simple docstring'''





    try:
        import faiss  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires faiss"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Any     ):



    '''simple docstring'''





    try:
        import regex  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires regex"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):



    '''simple docstring'''





    try:
        import elasticsearch  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires elasticsearch"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    try:
        import sqlalchemy  # noqa
    except ImportError:
        _lowerCAmelCase						      =   unittest.skip("test requires sqlalchemy"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       str     ):



    '''simple docstring'''





    if not config.TORCH_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires PyTorch"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    if not config.TF_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires TensorFlow"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Tuple     ):



    '''simple docstring'''





    if not config.JAX_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires JAX"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Dict     ):



    '''simple docstring'''





    if not config.PIL_AVAILABLE:
        _lowerCAmelCase						      =   unittest.skip("test requires Pillow"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       int     ):



    '''simple docstring'''





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


def 						__a(SCREAMING_SNAKE_CASE_	:       Any     ):



    '''simple docstring'''





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


def 						__a(SCREAMING_SNAKE_CASE_	:       List[str]     ):



    '''simple docstring'''





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


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





    def _require_spacy_model(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):
        try:
            import spacy  # noqa F401

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

    return _require_spacy_model


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





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


def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):



    '''simple docstring'''





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


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





    if not _run_slow_tests or _run_slow_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test is slow"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Dict     ):



    '''simple docstring'''





    if not _run_local_tests or _run_local_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test is local"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    if not _run_packaged_tests or _run_packaged_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test is packaged"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(SCREAMING_SNAKE_CASE_	:       Any     ):



    '''simple docstring'''





    if not _run_remote_tests or _run_remote_tests == 0:
        _lowerCAmelCase						      =   unittest.skip("test requires remote"     )(SCREAMING_SNAKE_CASE_     )
    return test_case


def 						__a(*SCREAMING_SNAKE_CASE_	:       Optional[Any]     ):



    '''simple docstring'''





    def decorate(cls	:       Any     ):
        for name, fn in cls.__dict__.items():
            if callable(SCREAMING_SNAKE_CASE_     ) and name.startswith("test"     ):
                for decorator in decorators:
                    _lowerCAmelCase						      =   decorator(SCREAMING_SNAKE_CASE_     )
                setattr(cls		,							SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_     )
        return cls

    return decorate

class  lowerCAmelCase_		(		__magic_name__		):
 pass







class  lowerCAmelCase_		(		__magic_name__		):
 __lowerCamelCase    :				Any								=       0
 __lowerCamelCase    :				Any								=       1
 __lowerCamelCase    :				Optional[int]								=       2







@contextmanager
def 						__a(SCREAMING_SNAKE_CASE_	:       List[str]=OfflineSimulationMode.CONNECTION_FAILS		,							SCREAMING_SNAKE_CASE_	:       Dict=1e-16     ):



    '''simple docstring'''





    _lowerCAmelCase						      =   requests.Session().request

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

    def raise_connection_error(SCREAMING_SNAKE_CASE_	:       List[str]		,							SCREAMING_SNAKE_CASE_	:       List[Any]		,							**SCREAMING_SNAKE_CASE_	:       int     ):
        raise requests.ConnectionError("Offline mode is enabled."		,							request=SCREAMING_SNAKE_CASE_     )

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


@contextmanager
def 						__a(*SCREAMING_SNAKE_CASE_	:       str		,							**SCREAMING_SNAKE_CASE_	:       Optional[int]     ):



    '''simple docstring'''





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


@contextmanager
def 						__a():



    '''simple docstring'''





    import gc

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


@contextmanager
def 						__a():



    '''simple docstring'''





    import gc

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


def 						__a(SCREAMING_SNAKE_CASE_	:       int		,							SCREAMING_SNAKE_CASE_	:       Tuple     ):



    '''simple docstring'''





    return deepcopy(SCREAMING_SNAKE_CASE_     ).integers(0		,							100		,							10     ).tolist() == deepcopy(SCREAMING_SNAKE_CASE_     ).integers(0		,							100		,							10     ).tolist()


def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):



    '''simple docstring'''





    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(SCREAMING_SNAKE_CASE_	:       Dict		,							*SCREAMING_SNAKE_CASE_	:       Optional[Any]		,							**SCREAMING_SNAKE_CASE_	:       Union[str, Any]     ):
        try:
            return func(*SCREAMING_SNAKE_CASE_		,							**SCREAMING_SNAKE_CASE_     )
        except HTTPError as err:
            if str(SCREAMING_SNAKE_CASE_     ).startswith("500"     ) or str(SCREAMING_SNAKE_CASE_     ).startswith("502"     ):
                pytest.xfail(str(SCREAMING_SNAKE_CASE_     )     )
            raise err

    return decorator.decorator(_wrapper		,							SCREAMING_SNAKE_CASE_     )

class  lowerCAmelCase_		:




 def __init__(						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Optional[Any]:
     _lowerCAmelCase						      =   returncode
     _lowerCAmelCase						      =   stdout
     _lowerCAmelCase						      =   stderr







async def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]		,							SCREAMING_SNAKE_CASE_	:       Dict     ):



    '''simple docstring'''





    while True:
        _lowerCAmelCase						      =   await stream.readline()
        if line:
            callback(SCREAMING_SNAKE_CASE_     )
        else:
            break


async def 						__a(SCREAMING_SNAKE_CASE_	:       Union[str, Any]		,							SCREAMING_SNAKE_CASE_	:       Any=None		,							SCREAMING_SNAKE_CASE_	:       Union[str, Any]=None		,							SCREAMING_SNAKE_CASE_	:       Dict=None		,							SCREAMING_SNAKE_CASE_	:       int=False		,							SCREAMING_SNAKE_CASE_	:       Tuple=False     ):



    '''simple docstring'''





    if echo:
        print("\nRunning: "		,							" ".join(SCREAMING_SNAKE_CASE_     )     )

    _lowerCAmelCase						      =   await asyncio.create_subprocess_exec(
        cmd[0]		,							*cmd[1:]		,							stdin=SCREAMING_SNAKE_CASE_		,							stdout=asyncio.subprocess.PIPE		,							stderr=asyncio.subprocess.PIPE		,							env=SCREAMING_SNAKE_CASE_		,							)

    # 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)

    _lowerCAmelCase						      =   []
    _lowerCAmelCase						      =   []

    def tee(SCREAMING_SNAKE_CASE_	:       List[Any]		,							SCREAMING_SNAKE_CASE_	:       Optional[Any]		,							SCREAMING_SNAKE_CASE_	:       List[str]		,							SCREAMING_SNAKE_CASE_	:       int=""     ):
        _lowerCAmelCase						      =   line.decode("utf-8"     ).rstrip()
        sink.append(SCREAMING_SNAKE_CASE_     )
        if not quiet:
            print(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							file=SCREAMING_SNAKE_CASE_     )

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            _read_stream(p.stdout		,							lambda SCREAMING_SNAKE_CASE_     : tee(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							sys.stdout		,							label="stdout:"     )     ),
            _read_stream(p.stderr		,							lambda SCREAMING_SNAKE_CASE_     : tee(SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_		,							sys.stderr		,							label="stderr:"     )     ),
        ]		,							timeout=SCREAMING_SNAKE_CASE_		,							)
    return _RunOutput(await p.wait()		,							SCREAMING_SNAKE_CASE_		,							SCREAMING_SNAKE_CASE_     )


def 						__a(SCREAMING_SNAKE_CASE_	:       List[str]		,							SCREAMING_SNAKE_CASE_	:       Union[str, Any]=None		,							SCREAMING_SNAKE_CASE_	:       Tuple=None		,							SCREAMING_SNAKE_CASE_	:       str=180		,							SCREAMING_SNAKE_CASE_	:       Optional[Any]=False		,							SCREAMING_SNAKE_CASE_	:       int=True     ):



    '''simple docstring'''





    _lowerCAmelCase						      =   asyncio.get_event_loop()
    _lowerCAmelCase						      =   loop.run_until_complete(
        _stream_subprocess(SCREAMING_SNAKE_CASE_		,							env=SCREAMING_SNAKE_CASE_		,							stdin=SCREAMING_SNAKE_CASE_		,							timeout=SCREAMING_SNAKE_CASE_		,							quiet=SCREAMING_SNAKE_CASE_		,							echo=SCREAMING_SNAKE_CASE_     )     )

    _lowerCAmelCase						      =   " ".join(SCREAMING_SNAKE_CASE_     )
    if result.returncode > 0:
        _lowerCAmelCase						      =   "\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 						__a():



    '''simple docstring'''





    _lowerCAmelCase						      =   os.environ.get("PYTEST_XDIST_WORKER"		,							"gw0"     )
    _lowerCAmelCase						      =   re.sub(R"^gw"		,							""		,							SCREAMING_SNAKE_CASE_		,							0		,							re.M     )
    return int(SCREAMING_SNAKE_CASE_     )





def 						__a():



    '''simple docstring'''





    _lowerCAmelCase						      =   29500
    _lowerCAmelCase						      =   pytest_xdist_worker_id()
    return port + uniq_delta









'''simple docstring'''


from ...configuration_utils import PretrainedConfig
from ...utils import logging


_SCREAMING_SNAKE_CASE									=				logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE									=				{
    "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json",
    "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json",
}

class  lowerCAmelCase_		(		__magic_name__		):
 __lowerCamelCase    :				Any								=       "falcon"
 __lowerCamelCase    :				List[str]								=       ["past_key_values"]




 def __init__(						self      ,  _lowerCAmelCase=65024      ,  _lowerCAmelCase=4544      ,  _lowerCAmelCase=32      ,  _lowerCAmelCase=71      ,  _lowerCAmelCase=1E-5      ,  _lowerCAmelCase=0.02      ,  _lowerCAmelCase=True      ,  _lowerCAmelCase=0.0      ,  _lowerCAmelCase=0.0      ,  _lowerCAmelCase=None      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=True      ,  _lowerCAmelCase=True      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=11      ,  _lowerCAmelCase=11      ,  **_lowerCAmelCase      ,  )     ->				Union[str, Any]:
     _lowerCAmelCase						      =   vocab_size
     # Backward compatibility with n_embed kwarg
     _lowerCAmelCase						      =   kwargs.pop("n_embed"      ,  _lowerCAmelCase		)
     _lowerCAmelCase						      =   hidden_size if n_embed is None else n_embed
     _lowerCAmelCase						      =   num_hidden_layers
     _lowerCAmelCase						      =   num_attention_heads
     _lowerCAmelCase						      =   layer_norm_epsilon
     _lowerCAmelCase						      =   initializer_range
     _lowerCAmelCase						      =   use_cache
     _lowerCAmelCase						      =   hidden_dropout
     _lowerCAmelCase						      =   attention_dropout

     _lowerCAmelCase						      =   bos_token_id
     _lowerCAmelCase						      =   eos_token_id
     _lowerCAmelCase						      =   num_attention_heads if num_kv_heads is None else num_kv_heads
     _lowerCAmelCase						      =   alibi
     _lowerCAmelCase						      =   new_decoder_architecture
     _lowerCAmelCase						      =   multi_query  # Ignored when new_decoder_architecture is True
     _lowerCAmelCase						      =   parallel_attn
     _lowerCAmelCase						      =   bias

     super().__init__(bos_token_id=_lowerCAmelCase      ,  eos_token_id=_lowerCAmelCase      ,  **_lowerCAmelCase		)




 @property
 def 				_snake_case (						self		)     ->				Optional[Any]:
     return self.hidden_size // self.num_attention_heads





 @property
 def 				_snake_case (						self		)     ->				Optional[Any]:
     return not self.alibi


