

import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
   import jax
   import jax.numpy as jnp

   from transformers.generation import (
       FlaxForcedBOSTokenLogitsProcessor,
       FlaxForcedEOSTokenLogitsProcessor,
       FlaxLogitsProcessorList,
       FlaxMinLengthLogitsProcessor,
       FlaxTemperatureLogitsWarper,
       FlaxTopKLogitsWarper,
       FlaxTopPLogitsWarper,
   )



@require_flax
class SCREAMING_SNAKE_CASE     (  unittest.TestCase			):
  """simple docstring"""






  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[int]	,							lowerCAmelCase			:   Any	,							lowerCAmelCase			:   Dict   )							->     Any:






     """simple docstring"""







     __lowerCAmelCase  :      Optional[int]    =						jnp.ones((batch_size, length)   ) / length
     return scores







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[Any]   )							->     Optional[int]:






     """simple docstring"""







     __lowerCAmelCase  :      Optional[Any]    =						None
     __lowerCAmelCase  :      Optional[Any]    =						20

     __lowerCAmelCase  :      Union[str, Any]    =						self._get_uniform_logits(batch_size=2	,							length=lowerCAmelCase   )

     # tweak scores to not be uniform anymore
     __lowerCAmelCase  :      List[str]    =						scores.at[1, 5].set((1 / length) + 0.1   )  # peak, 1st batch
     __lowerCAmelCase  :      Union[str, Any]    =						scores.at[1, 10].set((1 / length) - 0.4   )  # valley, 1st batch

     # compute softmax
     __lowerCAmelCase  :      str    =						jax.nn.softmax(lowerCAmelCase	,							axis=-1   )

     __lowerCAmelCase  :      List[str]    =						FlaxTemperatureLogitsWarper(temperature=0.5   )
     __lowerCAmelCase  :      Tuple    =						FlaxTemperatureLogitsWarper(temperature=1.3   )

     __lowerCAmelCase  :      Optional[Any]    =						jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase	,							scores.copy()	,							cur_len=lowerCAmelCase   )	,							axis=-1   )
     __lowerCAmelCase  :      Tuple    =						jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase	,							scores.copy()	,							cur_len=lowerCAmelCase   )	,							axis=-1   )

     # uniform distribution stays uniform
     self.assertTrue(jnp.allclose(probs[0, :]	,							warped_prob_sharp[0, :]	,							atol=1e-3   )   )
     self.assertTrue(jnp.allclose(probs[0, :]	,							warped_prob_smooth[0, :]	,							atol=1e-3   )   )

     # sharp peaks get higher, valleys get lower
     self.assertLess(probs[1, :].max()	,							warped_prob_sharp[1, :].max()   )
     self.assertGreater(probs[1, :].min()	,							warped_prob_sharp[1, :].min()   )

     # smooth peaks get lower, valleys get higher
     self.assertGreater(probs[1, :].max()	,							warped_prob_smooth[1, :].max()   )
     self.assertLess(probs[1, :].min()	,							warped_prob_smooth[1, :].min()   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[int]   )							->     Optional[int]:






     """simple docstring"""







     __lowerCAmelCase  :      Optional[int]    =						None
     __lowerCAmelCase  :      Tuple    =						10
     __lowerCAmelCase  :      str    =						2

     # create ramp distribution
     __lowerCAmelCase  :      Union[str, Any]    =						np.broadcast_to(np.arange(lowerCAmelCase   )[None, :]	,							(batch_size, vocab_size)   ).copy()
     __lowerCAmelCase  :      List[str]    =						ramp_logits[1:, : vocab_size // 2] + vocab_size

     __lowerCAmelCase  :      Optional[int]    =						FlaxTopKLogitsWarper(3   )

     __lowerCAmelCase  :      Optional[int]    =						top_k_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )

     # check that correct tokens are filtered
     self.assertListEqual(jnp.isinf(scores[0]   ).tolist()	,							7 * [True] + 3 * [False]   )
     self.assertListEqual(jnp.isinf(scores[1]   ).tolist()	,							2 * [True] + 3 * [False] + 5 * [True]   )

     # check special case
     __lowerCAmelCase  :      Optional[int]    =						5
     __lowerCAmelCase  :      List[Any]    =						FlaxTopKLogitsWarper(top_k=1	,							filter_value=0.0	,							min_tokens_to_keep=3   )

     __lowerCAmelCase  :      Tuple    =						np.broadcast_to(np.arange(lowerCAmelCase   )[None, :]	,							(batch_size, length)   ).copy()
     __lowerCAmelCase  :      Dict    =						top_k_warp_safety_check(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )

     # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
     self.assertListEqual((scores == 0.0).sum(axis=-1   ).tolist()	,							[2, 2]   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Any   )							->     Tuple:






     """simple docstring"""







     __lowerCAmelCase  :      Optional[Any]    =						None
     __lowerCAmelCase  :      List[str]    =						10
     __lowerCAmelCase  :      List[Any]    =						2

     # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
     __lowerCAmelCase  :      List[str]    =						np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]   )   )

     __lowerCAmelCase  :      Tuple    =						FlaxTopPLogitsWarper(0.8   )
     __lowerCAmelCase  :      Optional[Any]    =						np.exp(top_p_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )   )

     # dist should be filtered to keep min num values so that sum is >= top_p
     # exp (-inf) => 0
     __lowerCAmelCase  :      Tuple    =						np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]   )
     self.assertTrue(np.allclose(lowerCAmelCase	,							lowerCAmelCase	,							atol=1e-3   )   )

     # check edge cases with negative and extreme logits
     __lowerCAmelCase  :      Any    =						np.broadcast_to(np.arange(lowerCAmelCase   )[None, :]	,							(batch_size, vocab_size)   ).copy() - (
         vocab_size // 2
     )

     # make ramp_logits more extreme
     __lowerCAmelCase  :      str    =						ramp_logits[1] * 100.0

     # make sure at least 2 tokens are kept
     __lowerCAmelCase  :      int    =						FlaxTopPLogitsWarper(0.9	,							min_tokens_to_keep=2	,							filter_value=0.0   )
     __lowerCAmelCase  :      List[Any]    =						top_p_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )

     # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
     self.assertListEqual((filtered_dist != 0.0).sum(axis=-1   ).tolist()	,							[3, 2]   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[Any]   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase  :      Optional[Any]    =						20
     __lowerCAmelCase  :      Optional[Any]    =						4
     __lowerCAmelCase  :      int    =						0

     __lowerCAmelCase  :      Any    =						FlaxMinLengthLogitsProcessor(min_length=10	,							eos_token_id=lowerCAmelCase   )

     # check that min length is applied at length 5
     __lowerCAmelCase  :      List[Any]    =						ids_tensor((batch_size, 20)	,							vocab_size=20   )
     __lowerCAmelCase  :      Tuple    =						5
     __lowerCAmelCase  :      List[Any]    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Dict    =						min_dist_processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()	,							4 * [-float("""inf"""   )]   )

     # check that min length is not applied anymore at length 15
     __lowerCAmelCase  :      Optional[Any]    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      str    =						15
     __lowerCAmelCase  :      Any    =						min_dist_processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     self.assertFalse(jnp.isinf(lowerCAmelCase   ).any()   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Dict   )							->     List[Any]:






     """simple docstring"""







     __lowerCAmelCase  :      List[str]    =						20
     __lowerCAmelCase  :      str    =						4
     __lowerCAmelCase  :      Optional[int]    =						0

     __lowerCAmelCase  :      str    =						FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase   )

     # check that all scores are -inf except the bos_token_id score
     __lowerCAmelCase  :      Union[str, Any]    =						ids_tensor((batch_size, 1)	,							vocab_size=20   )
     __lowerCAmelCase  :      str    =						1
     __lowerCAmelCase  :      Dict    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      List[str]    =						logits_processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]   ).all()   )
     self.assertListEqual(scores[:, bos_token_id].tolist()	,							4 * [0]   )  # score for bos_token_id shold be zero

     # check that bos_token_id is not forced if current length is greater than 1
     __lowerCAmelCase  :      Optional[int]    =						3
     __lowerCAmelCase  :      Optional[Any]    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Optional[Any]    =						logits_processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     self.assertFalse(jnp.isinf(lowerCAmelCase   ).any()   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[Any]   )							->     Dict:






     """simple docstring"""







     __lowerCAmelCase  :      Any    =						20
     __lowerCAmelCase  :      str    =						4
     __lowerCAmelCase  :      Optional[int]    =						0
     __lowerCAmelCase  :      List[str]    =						5

     __lowerCAmelCase  :      int    =						FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase	,							eos_token_id=lowerCAmelCase   )

     # check that all scores are -inf except the eos_token_id when max_length is reached
     __lowerCAmelCase  :      str    =						ids_tensor((batch_size, 4)	,							vocab_size=20   )
     __lowerCAmelCase  :      List[Any]    =						4
     __lowerCAmelCase  :      str    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Union[str, Any]    =						logits_processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]   ).all()   )
     self.assertListEqual(scores[:, eos_token_id].tolist()	,							4 * [0]   )  # score for eos_token_id should be zero

     # check that eos_token_id is not forced if max_length is not reached
     __lowerCAmelCase  :      str    =						3
     __lowerCAmelCase  :      Any    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Optional[int]    =						logits_processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     self.assertFalse(jnp.isinf(lowerCAmelCase   ).any()   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   str   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase  :      str    =						4
     __lowerCAmelCase  :      Dict    =						10
     __lowerCAmelCase  :      Union[str, Any]    =						15
     __lowerCAmelCase  :      Any    =						2
     __lowerCAmelCase  :      str    =						1
     __lowerCAmelCase  :      Tuple    =						15

     # dummy input_ids and scores
     __lowerCAmelCase  :      str    =						ids_tensor((batch_size, sequence_length)	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Any    =						input_ids.copy()

     __lowerCAmelCase  :      Union[str, Any]    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Union[str, Any]    =						scores.copy()

     # instantiate all dist processors
     __lowerCAmelCase  :      List[Any]    =						FlaxTemperatureLogitsWarper(temperature=0.5   )
     __lowerCAmelCase  :      List[Any]    =						FlaxTopKLogitsWarper(3   )
     __lowerCAmelCase  :      Optional[int]    =						FlaxTopPLogitsWarper(0.8   )

     # instantiate all logits processors
     __lowerCAmelCase  :      Dict    =						FlaxMinLengthLogitsProcessor(min_length=10	,							eos_token_id=lowerCAmelCase   )
     __lowerCAmelCase  :      Optional[Any]    =						FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase   )
     __lowerCAmelCase  :      Optional[int]    =						FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase	,							eos_token_id=lowerCAmelCase   )

     __lowerCAmelCase  :      int    =						10

     # no processor list
     __lowerCAmelCase  :      int    =						temp_dist_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     __lowerCAmelCase  :      List[str]    =						top_k_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     __lowerCAmelCase  :      Tuple    =						top_p_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     __lowerCAmelCase  :      Union[str, Any]    =						min_dist_proc(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     __lowerCAmelCase  :      Tuple    =						bos_dist_proc(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
     __lowerCAmelCase  :      int    =						eos_dist_proc(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )

     # with processor list
     __lowerCAmelCase  :      str    =						FlaxLogitsProcessorList(
         [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]   )
     __lowerCAmelCase  :      Optional[Any]    =						processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )

     # scores should be equal
     self.assertTrue(jnp.allclose(lowerCAmelCase	,							lowerCAmelCase	,							atol=1e-3   )   )

     # input_ids should never be changed
     self.assertListEqual(input_ids.tolist()	,							input_ids_comp.tolist()   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Dict   )							->     Any:






     """simple docstring"""







     __lowerCAmelCase  :      Dict    =						4
     __lowerCAmelCase  :      Optional[int]    =						10
     __lowerCAmelCase  :      Optional[Any]    =						15
     __lowerCAmelCase  :      Optional[int]    =						2
     __lowerCAmelCase  :      List[Any]    =						1
     __lowerCAmelCase  :      Union[str, Any]    =						15

     # dummy input_ids and scores
     __lowerCAmelCase  :      Tuple    =						ids_tensor((batch_size, sequence_length)	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Tuple    =						input_ids.copy()

     __lowerCAmelCase  :      Optional[Any]    =						self._get_uniform_logits(lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      Any    =						scores.copy()

     # instantiate all dist processors
     __lowerCAmelCase  :      List[Any]    =						FlaxTemperatureLogitsWarper(temperature=0.5   )
     __lowerCAmelCase  :      str    =						FlaxTopKLogitsWarper(3   )
     __lowerCAmelCase  :      Tuple    =						FlaxTopPLogitsWarper(0.8   )

     # instantiate all logits processors
     __lowerCAmelCase  :      List[Any]    =						FlaxMinLengthLogitsProcessor(min_length=10	,							eos_token_id=lowerCAmelCase   )
     __lowerCAmelCase  :      Dict    =						FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase   )
     __lowerCAmelCase  :      List[str]    =						FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase	,							eos_token_id=lowerCAmelCase   )

     __lowerCAmelCase  :      List[str]    =						10

     # no processor list
     def run_no_processor_list(lowerCAmelCase			:   Dict	,							lowerCAmelCase			:   Union[str, Any]	,							lowerCAmelCase			:   int   ):
        __lowerCAmelCase  :      Tuple    =						temp_dist_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        __lowerCAmelCase  :      Tuple    =						top_k_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        __lowerCAmelCase  :      Union[str, Any]    =						top_p_warp(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        __lowerCAmelCase  :      Tuple    =						min_dist_proc(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        __lowerCAmelCase  :      str    =						bos_dist_proc(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        __lowerCAmelCase  :      Optional[int]    =						eos_dist_proc(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        return scores

     # with processor list
     def run_processor_list(lowerCAmelCase			:   List[Any]	,							lowerCAmelCase			:   Optional[int]	,							lowerCAmelCase			:   Union[str, Any]   ):
        __lowerCAmelCase  :      Any    =						FlaxLogitsProcessorList(
            [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]   )
        __lowerCAmelCase  :      Dict    =						processor(lowerCAmelCase	,							lowerCAmelCase	,							cur_len=lowerCAmelCase   )
        return scores

     __lowerCAmelCase  :      Any    =						jax.jit(lowerCAmelCase   )
     __lowerCAmelCase  :      List[str]    =						jax.jit(lowerCAmelCase   )

     __lowerCAmelCase  :      Optional[int]    =						jitted_run_no_processor_list(lowerCAmelCase	,							lowerCAmelCase	,							lowerCAmelCase   )
     __lowerCAmelCase  :      int    =						jitted_run_processor_list(lowerCAmelCase	,							lowerCAmelCase	,							lowerCAmelCase   )

     # scores should be equal
     self.assertTrue(jnp.allclose(lowerCAmelCase	,							lowerCAmelCase	,							atol=1e-3   )   )

     # input_ids should never be changed
     self.assertListEqual(input_ids.tolist()	,							input_ids_comp.tolist()   )





# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position

__UpperCAmelCase								=			"""2.13.1"""

import platform

import pyarrow
from packaging import version


if version.parse(platform.python_version()) < version.parse("""3.7"""):
   raise ImportWarning(
       """To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition."""
   )

if version.parse(pyarrow.__version__).major < 8:
   raise ImportWarning(
       """To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n"""
       """If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`."""
   )

del platform
del pyarrow
del version

from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
    list_datasets,
    list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
    NamedSplit,
    NamedSplitAll,
    Split,
    SplitBase,
    SplitDict,
    SplitGenerator,
    SplitInfo,
    SubSplitInfo,
    percent,
)
from .tasks import *
from .utils import *
from .utils import logging


# deprecated modules
from datasets import arrow_dataset as _arrow_dataset  # isort:skip
from datasets import utils as _utils  # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager  # isort:skip

__UpperCAmelCase								=			concatenate_datasets
__UpperCAmelCase								=			DownloadConfig
__UpperCAmelCase								=			DownloadManager
__UpperCAmelCase								=			DownloadMode
__UpperCAmelCase								=			DownloadConfig
__UpperCAmelCase								=			DownloadMode
__UpperCAmelCase								=			DownloadManager

del _arrow_dataset, _utils, _deprecated_download_manager


