





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 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     int			=    jnp.ones((batch_size, length)) / length
          return scores

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







          '''simple docstring'''

          a__						:     Any			=    None
          a__						:     str			=    20

          a__						:     Any			=    self._get_uniform_logits(batch_size=2 ,  length=lowercase)

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

          # compute softmax
          a__						:     Optional[Any]			=    jax.nn.softmax(lowercase ,  axis=-1)

          a__						:     int			=    FlaxTemperatureLogitsWarper(temperature=0.5)
          a__						:     Optional[Any]			=    FlaxTemperatureLogitsWarper(temperature=1.3)

          a__						:     Dict			=    jax.nn.softmax(temp_dist_warper_sharper(lowercase ,  scores.copy() ,  cur_len=lowercase) ,  axis=-1)
          a__						:     List[str]			=    jax.nn.softmax(temp_dist_warper_smoother(lowercase ,  scores.copy() ,  cur_len=lowercase) ,  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 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     Tuple			=    None
          a__						:     int			=    10
          a__						:     Optional[int]			=    2

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

          a__						:     List[Any]			=    FlaxTopKLogitsWarper(3)

          a__						:     str			=    top_k_warp(lowercase ,  lowercase ,  cur_len=lowercase)

          # 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
          a__						:     Tuple			=    5
          a__						:     Union[str, Any]			=    FlaxTopKLogitsWarper(top_k=1 ,  filter_value=0.0 ,  min_tokens_to_keep=3)

          a__						:     Dict			=    np.broadcast_to(np.arange(lowercase)[None, :] ,  (batch_size, length)).copy()
          a__						:     Union[str, Any]			=    top_k_warp_safety_check(lowercase ,  lowercase ,  cur_len=lowercase)

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

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







          '''simple docstring'''

          a__						:     Tuple			=    None
          a__						:     Optional[int]			=    10
          a__						:     Union[str, Any]			=    2

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

          a__						:     str			=    FlaxTopPLogitsWarper(0.8)
          a__						:     List[str]			=    np.exp(top_p_warp(lowercase ,  lowercase ,  cur_len=lowercase))

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

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

          # make ramp_logits more extreme
          a__						:     List[str]			=    ramp_logits[1] * 1_00.0

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

          # 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 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     Dict			=    20
          a__						:     str			=    4
          a__						:     Union[str, Any]			=    0

          a__						:     Union[str, Any]			=    FlaxMinLengthLogitsProcessor(min_length=10 ,  eos_token_id=lowercase)

          # check that min length is applied at length 5
          a__						:     List[str]			=    ids_tensor((batch_size, 20) ,  vocab_size=20)
          a__						:     Optional[int]			=    5
          a__						:     Tuple			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Tuple			=    min_dist_processor(lowercase ,  lowercase ,  cur_len=lowercase)
          self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() ,  4 * [-float('inf')])

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

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__						:     Dict			=    20
          a__						:     Any			=    4
          a__						:     Dict			=    0

          a__						:     List[str]			=    FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase)

          # check that all scores are -inf except the bos_token_id score
          a__						:     List[Any]			=    ids_tensor((batch_size, 1) ,  vocab_size=20)
          a__						:     List[Any]			=    1
          a__						:     int			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Any			=    logits_processor(lowercase ,  lowercase ,  cur_len=lowercase)
          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
          a__						:     List[str]			=    3
          a__						:     List[str]			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Union[str, Any]			=    logits_processor(lowercase ,  lowercase ,  cur_len=lowercase)
          self.assertFalse(jnp.isinf(lowercase).any())

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







          '''simple docstring'''

          a__						:     Union[str, Any]			=    20
          a__						:     str			=    4
          a__						:     Union[str, Any]			=    0
          a__						:     Tuple			=    5

          a__						:     Optional[Any]			=    FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase ,  eos_token_id=lowercase)

          # check that all scores are -inf except the eos_token_id when max_length is reached
          a__						:     str			=    ids_tensor((batch_size, 4) ,  vocab_size=20)
          a__						:     Optional[Any]			=    4
          a__						:     Union[str, Any]			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Optional[int]			=    logits_processor(lowercase ,  lowercase ,  cur_len=lowercase)
          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
          a__						:     Tuple			=    3
          a__						:     Any			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Tuple			=    logits_processor(lowercase ,  lowercase ,  cur_len=lowercase)
          self.assertFalse(jnp.isinf(lowercase).any())

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     Optional[int]			=    4
          a__						:     Optional[Any]			=    10
          a__						:     Tuple			=    15
          a__						:     Optional[Any]			=    2
          a__						:     List[Any]			=    1
          a__						:     List[str]			=    15

          # dummy input_ids and scores
          a__						:     Optional[Any]			=    ids_tensor((batch_size, sequence_length) ,  lowercase)
          a__						:     str			=    input_ids.copy()

          a__						:     List[Any]			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Optional[int]			=    scores.copy()

          # instantiate all dist processors
          a__						:     Dict			=    FlaxTemperatureLogitsWarper(temperature=0.5)
          a__						:     str			=    FlaxTopKLogitsWarper(3)
          a__						:     Optional[int]			=    FlaxTopPLogitsWarper(0.8)

          # instantiate all logits processors
          a__						:     Optional[int]			=    FlaxMinLengthLogitsProcessor(min_length=10 ,  eos_token_id=lowercase)
          a__						:     Union[str, Any]			=    FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase)
          a__						:     Union[str, Any]			=    FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase ,  eos_token_id=lowercase)

          a__						:     int			=    10

          # no processor list
          a__						:     Any			=    temp_dist_warp(lowercase ,  lowercase ,  cur_len=lowercase)
          a__						:     int			=    top_k_warp(lowercase ,  lowercase ,  cur_len=lowercase)
          a__						:     Optional[Any]			=    top_p_warp(lowercase ,  lowercase ,  cur_len=lowercase)
          a__						:     List[Any]			=    min_dist_proc(lowercase ,  lowercase ,  cur_len=lowercase)
          a__						:     str			=    bos_dist_proc(lowercase ,  lowercase ,  cur_len=lowercase)
          a__						:     Optional[int]			=    eos_dist_proc(lowercase ,  lowercase ,  cur_len=lowercase)

          # with processor list
          a__						:     Dict			=    FlaxLogitsProcessorList(
              [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc])
          a__						:     List[str]			=    processor(lowercase ,  lowercase ,  cur_len=lowercase)

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

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

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     List[str]			=    4
          a__						:     List[Any]			=    10
          a__						:     Tuple			=    15
          a__						:     int			=    2
          a__						:     Any			=    1
          a__						:     Tuple			=    15

          # dummy input_ids and scores
          a__						:     Optional[int]			=    ids_tensor((batch_size, sequence_length) ,  lowercase)
          a__						:     Union[str, Any]			=    input_ids.copy()

          a__						:     List[Any]			=    self._get_uniform_logits(lowercase ,  lowercase)
          a__						:     Optional[int]			=    scores.copy()

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

          # instantiate all logits processors
          a__						:     List[str]			=    FlaxMinLengthLogitsProcessor(min_length=10 ,  eos_token_id=lowercase)
          a__						:     int			=    FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase)
          a__						:     str			=    FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase ,  eos_token_id=lowercase)

          a__						:     Union[str, Any]			=    10

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

          # with processor list
          def run_processor_list(lowercase ,  lowercase ,  lowercase):
                 a__						:     str			=    FlaxLogitsProcessorList(
                     [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc])
                 a__						:     Dict			=    processor(lowercase ,  lowercase ,  cur_len=lowercase)
                 return scores

          a__						:     Any			=    jax.jit(lowercase)
          a__						:     Tuple			=    jax.jit(lowercase)

          a__						:     Union[str, Any]			=    jitted_run_no_processor_list(lowercase ,  lowercase ,  lowercase)
          a__						:     List[Any]			=    jitted_run_processor_list(lowercase ,  lowercase ,  lowercase)

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

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









from __future__ import annotations

from collections.abc import Callable



def A_     (		A__		,				A__		,				A__		,				A__ = 100		,				)  ->		float:
       a__						:     Dict			=    x_start
       a__						:     Any			=    fnc(A__    )
       a__						:     Optional[int]			=    0.0
       for _ in range(A__    ):
              # Approximates small segments of curve as linear and solve
              # for trapezoidal area
              a__						:     Union[str, Any]			=    (x_end - x_start) / steps + xa
              a__						:     str			=    fnc(A__    )
              area += abs(fxa + fxa    ) * (xa - xa) / 2
              # Increment step
              a__						:     Optional[Any]			=    xa
              a__						:     Optional[int]			=    fxa
       return area


if __name__ == "__main__":



    def A_     (		A__    )  ->		List[str]:
           return x**3 + x**2

    print("""f(x) = x^3 + x^2""")
    print("""The area between the curve, x = -5, x = 5 and the x axis is:""")
    lowercase				:	Union[str, Any]      						=  1_0
    while i <= 1_0_0_0_0_0:
        print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""")
        i *= 1_0


