



"""simple docstring"""
import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


UpperCAmelCase    :		Dict      =			get_logger(__name__)


UpperCAmelCase    :		Dict      =			R"\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n"


class  SCREAMING_SNAKE_CASE__			:

    @add_start_docstrings(__a)
    def __call__(					self      :					Dict			,	lowerCAmelCase_      :					Union[str, Any]			,	lowerCAmelCase_      :					Optional[int]):







      """simple docstring"""







      raise NotImplementedError(
          F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')







class  SCREAMING_SNAKE_CASE__			:

    @add_start_docstrings(__a)
    def __call__(					self      :					List[str]			,	lowerCAmelCase_      :					str			,	lowerCAmelCase_      :					List[str]):







      """simple docstring"""







      raise NotImplementedError(
          F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    @add_start_docstrings(__a)
    def __call__(					self      :					List[str]			,	lowerCAmelCase_      :					List[Any]			,	lowerCAmelCase_      :					List[str]			,	lowerCAmelCase_      :					Optional[Any]			,	**lowerCAmelCase_      :					Optional[int]):







      """simple docstring"""







      for processor in self:
        lowercase_             =			inspect.signature(processor.__call__).parameters
        if len(__a) > 3:
          if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
            raise ValueError(
                F'''Make sure that all the required parameters: {list(function_args.keys())} for '''
                F'''{processor.__class__} are passed to the logits processor.''')
          lowercase_             =			processor(__a			,	__a			,	__a			,	**__a)
        else:
          lowercase_             =			processor(__a			,	__a			,	__a)
      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					Optional[int]			,	lowerCAmelCase_      :					Dict):







      """simple docstring"""







      if not isinstance(__a			,	__a) or not (temperature > 0):
        raise ValueError(F'''`temperature` has to be a strictly positive float, but is {temperature}''')

      lowercase_             =			temperature




    def __call__(					self      :					List[str]			,	lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					int			,	lowerCAmelCase_      :					str):







      """simple docstring"""







      lowercase_             =			scores / self.temperature
      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					str			,	lowerCAmelCase_      :					Any			,	lowerCAmelCase_      :					int = -float("""Inf""")			,	lowerCAmelCase_      :					Union[str, Any] = 1):







      """simple docstring"""







      if not isinstance(__a			,	__a) or (top_p < 0 or top_p > 1.0):
        raise ValueError(F'''`top_p` has to be a float > 0 and < 1, but is {top_p}''')
      if not isinstance(__a			,	__a) or (min_tokens_to_keep < 1):
        raise ValueError(F'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''')

      lowercase_             =			top_p
      lowercase_             =			filter_value
      lowercase_             =			min_tokens_to_keep




    def __call__(					self      :					List[Any]			,	lowerCAmelCase_      :					Dict			,	lowerCAmelCase_      :					Tuple			,	lowerCAmelCase_      :					int):







      """simple docstring"""







      lowercase_       ,     lowercase_             =			lax.top_k(__a			,	scores.shape[-1])

      lowercase_             =			jnp.full_like(__a			,	self.filter_value)
      lowercase_             =			jax.nn.softmax(__a			,	axis=-1).cumsum(axis=-1)
      lowercase_             =			cumulative_probs < self.top_p

      # include the token that is higher than top_p as well
      lowercase_             =			jnp.roll(__a			,	1)
      score_mask |= score_mask.at[:, 0].set(__a)

      # min tokens to keep
      lowercase_             =			score_mask.at[:, : self.min_tokens_to_keep].set(__a)

      lowercase_             =			jnp.where(__a			,	__a			,	__a)
      lowercase_             =			jax.lax.sort_key_val(__a			,	__a)[-1]

      return next_scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					List[Any]			,	lowerCAmelCase_      :					Union[str, Any]			,	lowerCAmelCase_      :					Optional[Any] = -float("""Inf""")			,	lowerCAmelCase_      :					int = 1):







      """simple docstring"""







      if not isinstance(__a			,	__a) or top_k <= 0:
        raise ValueError(F'''`top_k` has to be a strictly positive integer, but is {top_k}''')

      lowercase_             =			max(__a			,	__a)
      lowercase_             =			filter_value




    def __call__(					self      :					Optional[int]			,	lowerCAmelCase_      :					List[str]			,	lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					Dict):







      """simple docstring"""







      lowercase_       ,     lowercase_             =			scores.shape
      lowercase_             =			jnp.full(batch_size * vocab_size			,	self.filter_value)

      lowercase_             =			min(self.top_k			,	scores.shape[-1])  # Safety check
      lowercase_       ,     lowercase_             =			lax.top_k(__a			,	__a)
      lowercase_             =			jnp.broadcast_to((jnp.arange(__a) * vocab_size)[:, None]			,	(batch_size, topk)).flatten()
      lowercase_             =			topk_scores.flatten()
      lowercase_             =			topk_indices.flatten() + shift

      lowercase_             =			next_scores_flat.at[topk_indices_flat].set(__a)
      lowercase_             =			next_scores_flat.reshape(__a			,	__a)
      return next_scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					List[str]			,	lowerCAmelCase_      :					str):







      """simple docstring"""







      lowercase_             =			bos_token_id




    def __call__(					self      :					int			,	lowerCAmelCase_      :					List[Any]			,	lowerCAmelCase_      :					Optional[Any]			,	lowerCAmelCase_      :					Union[str, Any]):







      """simple docstring"""







      lowercase_             =			jnp.full(scores.shape			,	-float("""inf"""))

      lowercase_             =			1 - jnp.bool_(cur_len - 1)

      lowercase_             =			jnp.where(__a			,	new_scores.at[:, self.bos_token_id].set(0)			,	__a)

      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					Tuple			,	lowerCAmelCase_      :					int			,	lowerCAmelCase_      :					Dict):







      """simple docstring"""







      lowercase_             =			max_length
      lowercase_             =			eos_token_id




    def __call__(					self      :					Union[str, Any]			,	lowerCAmelCase_      :					List[str]			,	lowerCAmelCase_      :					List[Any]			,	lowerCAmelCase_      :					Union[str, Any]):







      """simple docstring"""







      lowercase_             =			jnp.full(scores.shape			,	-float("""inf"""))

      lowercase_             =			1 - jnp.bool_(cur_len - self.max_length + 1)

      lowercase_             =			jnp.where(__a			,	new_scores.at[:, self.eos_token_id].set(0)			,	__a)

      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					Any			,	lowerCAmelCase_      :					str			,	lowerCAmelCase_      :					Dict):







      """simple docstring"""







      if not isinstance(__a			,	__a) or min_length < 0:
        raise ValueError(F'''`min_length` has to be a positive integer, but is {min_length}''')

      if not isinstance(__a			,	__a) or eos_token_id < 0:
        raise ValueError(F'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''')

      lowercase_             =			min_length
      lowercase_             =			eos_token_id




    def __call__(					self      :					Dict			,	lowerCAmelCase_      :					List[str]			,	lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					Optional[Any]):







      """simple docstring"""







      lowercase_             =			1 - jnp.clip(cur_len - self.min_length			,	0			,	1)

      lowercase_             =			jnp.where(__a			,	scores.at[:, self.eos_token_id].set(-float("""inf"""))			,	__a)

      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					Optional[int]			,	lowerCAmelCase_      :					Optional[Any]			,	lowerCAmelCase_      :					int):







      """simple docstring"""







      lowercase_             =			list(__a)
      lowercase_             =			begin_index




    def __call__(					self      :					Optional[Any]			,	lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					Tuple):







      """simple docstring"""







      lowercase_             =			1 - jnp.bool_(cur_len - self.begin_index)

      lowercase_             =			jnp.where(__a			,	scores.at[:, self.begin_suppress_tokens].set(-float("""inf"""))			,	__a)

      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					List[str]			,	lowerCAmelCase_      :					Optional[int]):







      """simple docstring"""







      lowercase_             =			list(__a)




    def __call__(					self      :					int			,	lowerCAmelCase_      :					Tuple			,	lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					List[str]):







      """simple docstring"""







      lowercase_             =			scores.at[..., self.suppress_tokens].set(-float("""inf"""))

      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					Union[str, Any]			,	lowerCAmelCase_      :					str):







      """simple docstring"""







      lowercase_             =			dict(__a)
      # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
      # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
      # Indexes without forced tokens will have a negative value.
      lowercase_             =			jnp.ones((max(force_token_map.keys()) + 1)			,	dtype=jnp.intaa) * -1
      for index, token in force_token_map.items():
        if token is not None:
          lowercase_             =			force_token_array.at[index].set(__a)
      lowercase_             =			jnp.intaa(__a)




    def __call__(					self      :					Optional[Any]			,	lowerCAmelCase_      :					Tuple			,	lowerCAmelCase_      :					Dict			,	lowerCAmelCase_      :					Any):







      """simple docstring"""







      def _force_token(lowerCAmelCase_      :					List[str]):
        lowercase_             =			scores.shape[0]
        lowercase_             =			self.force_token_array[generation_idx]

        lowercase_             =			jnp.ones_like(__a			,	dtype=scores.dtype) * -float("""inf""")
        lowercase_             =			jnp.zeros((batch_size, 1)			,	dtype=scores.dtype)
        lowercase_             =			lax.dynamic_update_slice(__a			,	__a			,	(0, current_token))
        return new_scores

      lowercase_             =			lax.cond(
          cur_len >= self.force_token_array.shape[0]			,	lambda: scores			,	lambda: lax.cond(
              self.force_token_array[cur_len] >= 0			,	lambda: _force_token(__a)			,	lambda: scores			,	)			,	)
      return scores







class  SCREAMING_SNAKE_CASE__			(				lowerCAmelCase__ ):

    def __init__(					self      :					int			,	lowerCAmelCase_      :					List[Any]			,	lowerCAmelCase_      :					Optional[Any]			,	lowerCAmelCase_      :					int):







      """simple docstring"""







      lowercase_             =			generate_config.eos_token_id
      lowercase_             =			generate_config.no_timestamps_token_id
      lowercase_             =			generate_config.no_timestamps_token_id + 1

      lowercase_             =			decoder_input_length + 1

      if generate_config.is_multilingual:
        # room for language token and task token
        self.begin_index += 2
      if hasattr(__a			,	"""max_initial_timestamp_index"""):
        lowercase_             =			generate_config.max_initial_timestamp_index
      else:
        lowercase_             =			model_config.vocab_size
      if self.max_initial_timestamp_index is None:
        lowercase_             =			model_config.vocab_size




    def __call__(					self      :					List[str]			,	lowerCAmelCase_      :					Tuple			,	lowerCAmelCase_      :					Dict			,	lowerCAmelCase_      :					Optional[int]):







      """simple docstring"""







      lowercase_             =			scores.at[:, self.no_timestamps_token_id].set(-float("""inf"""))

      def handle_pairs(lowerCAmelCase_      :					Optional[int]			,	lowerCAmelCase_      :					int):
        lowercase_             =			jnp.where((cur_len - self.begin_index) >= 1			,	__a			,	__a)
        lowercase_             =			jnp.where(
            input_ids_k[cur_len - 1] >= self.timestamp_begin			,	True and last_was_timestamp			,	__a			,	)

        lowercase_             =			jnp.where((cur_len - self.begin_index) < 2			,	__a			,	__a)
        lowercase_             =			jnp.where(
            input_ids_k[cur_len - 2] >= self.timestamp_begin			,	__a			,	__a			,	)

        return jnp.where(
            __a			,	jnp.where(
                penultimate_was_timestamp > 0			,	scores_k.at[self.timestamp_begin :].set(-float("""inf"""))			,	scores_k.at[: self.eos_token_id].set(-float("""inf"""))			,	)			,	__a			,	)

      lowercase_             =			jax.vmap(__a)(__a			,	__a)

      lowercase_             =			jnp.where(cur_len == self.begin_index			,	__a			,	__a)
      lowercase_             =			jnp.where(
          self.max_initial_timestamp_index is not None			,	True and apply_max_initial_timestamp			,	__a			,	)

      lowercase_             =			self.timestamp_begin + self.max_initial_timestamp_index

      lowercase_             =			jnp.where(
          __a			,	scores.at[:, last_allowed + 1 :].set(-float("""inf"""))			,	__a			,	)

      # if sum of probability over timestamps is above any other token, sample timestamp
      lowercase_             =			jax.nn.log_softmax(__a			,	axis=-1)

      def handle_cumulative_probs(lowerCAmelCase_      :					Dict			,	lowerCAmelCase_      :					Union[str, Any]):
        lowercase_             =			jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]			,	axis=-1)
        lowercase_             =			jnp.max(logprobs_k[: self.timestamp_begin])
        return jnp.where(
            timestamp_logprob > max_text_token_logprob			,	scores_k.at[: self.timestamp_begin].set(-float("""inf"""))			,	__a			,	)

      lowercase_             =			jax.vmap(__a)(__a			,	__a)

      return scores





"""simple docstring"""


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
A	:  List[str]            =     pytest.mark.integration


A	:  Optional[Any]            =     {"comet"}
A	:  int            =     importlib.util.find_spec("fairseq") is not None

A	:  Union[str, Any]            =     {"code_eval"}
A	:  Dict            =     os.name == "nt"

A	:  Dict            =     {"bertscore", "frugalscore", "perplexity"}
A	:  Any            =     importlib.util.find_spec("transformers") is not None


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
									self.skipTest("\"test requires Fairseq\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
									self.skipTest("\"test requires transformers\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
									self.skipTest("\"test not supported on Windows\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						):

			'''simple docstring'''




			__lowerCAmelCase							       =     [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )]
			return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names()						)
@for_all_test_methods(
    lowerCAmelCase__			,lowerCAmelCase__			,lowerCAmelCase__						)
@local
class     _UpperCamelCase    (  parameterized.TestCase						):
							'''simple docstring'''







							__UpperCAmelCase		:       Any							 ={}
							__UpperCAmelCase		:       List[str]							 =None

							@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"      )
							@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"      )
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										__lowerCAmelCase							       =     datasets.load.import_main_class(metric_module.__name__       ,  dataset=__a      )
										# check parameters
										__lowerCAmelCase							       =     inspect.signature(metric._compute      ).parameters
										self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()      )      )  # no **kwargs
										# run doctest
										with self.patch_intensive_calls(__a       ,  metric_module.__name__      ):
													with self.use_local_metrics():
																try:
																			__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
																except doctest.UnexpectedException as e:
																			raise e.exc_info[1]  # raise the exception that doctest caught
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

							@slow
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										# run doctest
										with self.use_local_metrics():
													__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

							@contextmanager
							def      snake_case							(	self       ,  __a       ,  __a      ):
										if metric_name in self.INTENSIVE_CALLS_PATCHER:
													with self.INTENSIVE_CALLS_PATCHER[metric_name](__a      ):
																yield
										else:
													yield

							@contextmanager
							def      snake_case							(	self      ):
										def load_local_metric(__a       ,  *__a       ,  **__a      ):
													return load_metric(os.path.join("metrics"       ,  __a      )       ,  *__a       ,  **__a      )

										with patch("datasets.load_metric"      ) as mock_load_metric:
													__lowerCAmelCase							       =     load_local_metric
													yield



							@classmethod
							def      snake_case							(	cls       ,  __a      ):
										def wrapper(__a      ):
													__lowerCAmelCase							       =     contextmanager(__a      )
													__lowerCAmelCase							       =     patcher
													return patcher

										return wrapper


@LocalMetricTest.register_intensive_calls_patcher("bleurt" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import tensorflow.compat.va as tf
			from bleurt.score import Predictor

			tf.flags.DEFINE_string("sv"       ,					""       ,					"" )  # handle pytest cli flags
			class     _UpperCamelCase    (  lowerCAmelCase__						):
										'''simple docstring'''







										def      snake_case							(	self       ,  __a      ):
													assert len(input_dict["input_ids"]      ) == 2
													return np.array([1.0_3, 1.0_4]      )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
			with patch("bleurt.score._create_predictor" ) as mock_create_predictor:
						__lowerCAmelCase							       =     MockedPredictor()
						yield


@LocalMetricTest.register_intensive_calls_patcher("bertscore" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import torch

			def bert_cos_score_idf(_UpperCamelCase       ,					_UpperCamelCase       ,					*_UpperCamelCase       ,					**_UpperCamelCase ):
						return torch.tensor([[1.0, 1.0, 1.0]] * len(_UpperCamelCase ) )

			# mock get_model which is supposed to do download a bert model
			# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
			with patch("bert_score.scorer.get_model" ), patch(
			    "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf:
						__lowerCAmelCase							       =     bert_cos_score_idf
						yield


@LocalMetricTest.register_intensive_calls_patcher("comet" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			def load_from_checkpoint(_UpperCamelCase ):
						class     _UpperCamelCase    :
													'''simple docstring'''







													def      snake_case							(	self       ,  __a       ,  *__a       ,  **__a      ):
																assert len(__a      ) == 2
																__lowerCAmelCase							       =     [0.1_9, 0.9_2]
																return scores, sum(__a      ) / len(__a      )
						return Model()

			# mock load_from_checkpoint which is supposed to do download a bert model
			# mock load_from_checkpoint which is supposed to do download a bert model
			with patch("comet.download_model" ) as mock_download_model:
						__lowerCAmelCase							       =     None
						with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint:
									__lowerCAmelCase							       =     load_from_checkpoint
									yield


def _lowerCamelCase      (						):

			'''simple docstring'''




			__lowerCAmelCase							       =     load_metric(os.path.join("metrics"       ,					"seqeval" ) )
			__lowerCAmelCase							       =     "ERROR"
			__lowerCAmelCase							       =     f"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"
			with pytest.raises(_UpperCamelCase       ,					match=re.escape(_UpperCamelCase ) ):
						metric.compute(predictions=[]       ,					references=[]       ,					scheme=_UpperCamelCase )




