


'''simple docstring'''
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 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

       """simple docstring"""







       __A  :		Union[str, Any]       =			jnp.ones((batch_size, length)						) / length
       return scores


 def  snake_case__   (      self						):

       """simple docstring"""







       __A  :		str       =			None
       __A  :		Optional[Any]       =			20

       __A  :		Tuple       =			self._get_uniform_logits(batch_size=2      ,      length=__lowercase						)

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

       # compute softmax
       __A  :		Optional[int]       =			jax.nn.softmax(__lowercase      ,      axis=-1						)

       __A  :		Dict       =			FlaxTemperatureLogitsWarper(temperature=0.5						)
       __A  :		List[Any]       =			FlaxTemperatureLogitsWarper(temperature=1.3						)

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

       """simple docstring"""







       __A  :		Optional[int]       =			None
       __A  :		Optional[int]       =			10
       __A  :		Optional[int]       =			2

       # create ramp distribution
       __A  :		Tuple       =			np.broadcast_to(np.arange(__lowercase						)[None, :]      ,      (batch_size, vocab_size)						).copy()
       __A  :		str       =			ramp_logits[1:, : vocab_size // 2] + vocab_size

       __A  :		Dict       =			FlaxTopKLogitsWarper(3						)

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

       __A  :		List[Any]       =			np.broadcast_to(np.arange(__lowercase						)[None, :]      ,      (batch_size, length)						).copy()
       __A  :		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  snake_case__   (      self						):

       """simple docstring"""







       __A  :		Optional[Any]       =			None
       __A  :		Union[str, Any]       =			10
       __A  :		Optional[Any]       =			2

       # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
       __A  :		Any       =			np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]]						)						)

       __A  :		int       =			FlaxTopPLogitsWarper(0.8						)
       __A  :		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  :		Dict       =			np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]]						)
       self.assertTrue(np.allclose(__lowercase      ,      __lowercase      ,      atol=1E-3						)						)

       # check edge cases with negative and extreme logits
       __A  :		Optional[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_0_0.0

       # make sure at least 2 tokens are kept
       __A  :		Any       =			FlaxTopPLogitsWarper(0.9      ,      min_tokens_to_keep=2      ,      filter_value=0.0						)
       __A  :		Tuple       =			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  snake_case__   (      self						):

       """simple docstring"""







       __A  :		Union[str, Any]       =			20
       __A  :		int       =			4
       __A  :		Optional[int]       =			0

       __A  :		int       =			FlaxMinLengthLogitsProcessor(min_length=10      ,      eos_token_id=__lowercase						)

       # check that min length is applied at length 5
       __A  :		Dict       =			ids_tensor((batch_size, 20)      ,      vocab_size=20						)
       __A  :		Tuple       =			5
       __A  :		List[str]       =			self._get_uniform_logits(__lowercase      ,      __lowercase						)
       __A  :		List[Any]       =			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  :		Any       =			self._get_uniform_logits(__lowercase      ,      __lowercase						)
       __A  :		Dict       =			15
       __A  :		Any       =			min_dist_processor(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       self.assertFalse(jnp.isinf(__lowercase						).any()						)


 def  snake_case__   (      self						):

       """simple docstring"""







       __A  :		Dict       =			20
       __A  :		Union[str, Any]       =			4
       __A  :		Optional[int]       =			0

       __A  :		List[Any]       =			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowercase						)

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


 def  snake_case__   (      self						):

       """simple docstring"""







       __A  :		str       =			20
       __A  :		List[str]       =			4
       __A  :		List[Any]       =			0
       __A  :		List[str]       =			5

       __A  :		int       =			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  :		int       =			ids_tensor((batch_size, 4)      ,      vocab_size=20						)
       __A  :		Union[str, Any]       =			4
       __A  :		Optional[int]       =			self._get_uniform_logits(__lowercase      ,      __lowercase						)
       __A  :		List[str]       =			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  :		Optional[Any]       =			3
       __A  :		str       =			self._get_uniform_logits(__lowercase      ,      __lowercase						)
       __A  :		List[str]       =			logits_processor(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       self.assertFalse(jnp.isinf(__lowercase						).any()						)


 def  snake_case__   (      self						):

       """simple docstring"""







       __A  :		Any       =			4
       __A  :		List[str]       =			10
       __A  :		Dict       =			15
       __A  :		Optional[Any]       =			2
       __A  :		List[Any]       =			1
       __A  :		Any       =			15

       # dummy input_ids and scores
       __A  :		int       =			ids_tensor((batch_size, sequence_length)      ,      __lowercase						)
       __A  :		str       =			input_ids.copy()

       __A  :		Union[str, Any]       =			self._get_uniform_logits(__lowercase      ,      __lowercase						)
       __A  :		Dict       =			scores.copy()

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

       # instantiate all logits processors
       __A  :		Tuple       =			FlaxMinLengthLogitsProcessor(min_length=10      ,      eos_token_id=__lowercase						)
       __A  :		Any       =			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowercase						)
       __A  :		int       =			FlaxForcedEOSTokenLogitsProcessor(max_length=__lowercase      ,      eos_token_id=__lowercase						)

       __A  :		Optional[Any]       =			10

       # no processor list
       __A  :		Any       =			temp_dist_warp(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       __A  :		List[str]       =			top_k_warp(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       __A  :		Dict       =			top_p_warp(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       __A  :		str       =			min_dist_proc(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       __A  :		Optional[Any]       =			bos_dist_proc(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
       __A  :		Any       =			eos_dist_proc(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)

       # with processor list
       __A  :		Optional[Any]       =			FlaxLogitsProcessorList(
           [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]						)
       __A  :		Tuple       =			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  snake_case__   (      self						):

       """simple docstring"""







       __A  :		List[str]       =			4
       __A  :		Dict       =			10
       __A  :		str       =			15
       __A  :		str       =			2
       __A  :		List[str]       =			1
       __A  :		Any       =			15

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

       __A  :		Dict       =			self._get_uniform_logits(__lowercase      ,      __lowercase						)
       __A  :		Any       =			scores.copy()

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

       # instantiate all logits processors
       __A  :		int       =			FlaxMinLengthLogitsProcessor(min_length=10      ,      eos_token_id=__lowercase						)
       __A  :		Dict       =			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowercase						)
       __A  :		Tuple       =			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  :		List[Any]       =			temp_dist_warp(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
             __A  :		Optional[int]       =			top_k_warp(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
             __A  :		Optional[int]       =			top_p_warp(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
             __A  :		Optional[int]       =			min_dist_proc(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
             __A  :		int       =			bos_dist_proc(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
             __A  :		Dict       =			eos_dist_proc(__lowercase      ,      __lowercase      ,      cur_len=__lowercase						)
             return scores

       # with processor list
       def run_processor_list(__lowercase      ,      __lowercase      ,      __lowercase						):
             __A  :		Dict       =			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  :		str       =			jax.jit(__lowercase						)
       __A  :		Optional[Any]       =			jax.jit(__lowercase						)

       __A  :		List[str]       =			jitted_run_no_processor_list(__lowercase      ,      __lowercase      ,      __lowercase						)
       __A  :		int       =			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()						)










'''simple docstring'''
from math import pi, sqrt, tan


def 			_lowercase       (				UpperCamelCase__       :					float			):
 if side_length < 0:
  raise ValueError('surface_area_cube() only accepts non-negative values'			)
 return 6 * side_length**2


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if length < 0 or breadth < 0 or height < 0:
  raise ValueError('surface_area_cuboid() only accepts non-negative values'			)
 return 2 * ((length * breadth) + (breadth * height) + (length * height))


def 			_lowercase       (				UpperCamelCase__       :					float			):
 if radius < 0:
  raise ValueError('surface_area_sphere() only accepts non-negative values'			)
 return 4 * pi * radius**2


def 			_lowercase       (				UpperCamelCase__       :					float			):
 if radius < 0:
  raise ValueError('surface_area_hemisphere() only accepts non-negative values'			)
 return 3 * pi * radius**2


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if radius < 0 or height < 0:
  raise ValueError('surface_area_cone() only accepts non-negative values'			)
 return pi * radius * (radius + (height**2 + radius**2) ** 0.5)


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if radius_a < 0 or radius_a < 0 or height < 0:
  raise ValueError(
      'surface_area_conical_frustum() only accepts non-negative values'			)
 __A  :		Optional[Any]       =			(height**2 + (radius_a - radius_a) ** 2) ** 0.5
 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2)


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if radius < 0 or height < 0:
  raise ValueError('surface_area_cylinder() only accepts non-negative values'			)
 return 2 * pi * radius * (height + radius)


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if torus_radius < 0 or tube_radius < 0:
  raise ValueError('surface_area_torus() only accepts non-negative values'			)
 if torus_radius < tube_radius:
  raise ValueError(
      'surface_area_torus() does not support spindle or self intersecting tori'			)
 return 4 * pow(UpperCamelCase__,				2			) * torus_radius * tube_radius


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if length < 0 or width < 0:
  raise ValueError('area_rectangle() only accepts non-negative values'			)
 return length * width


def 			_lowercase       (				UpperCamelCase__       :					float			):
 if side_length < 0:
  raise ValueError('area_square() only accepts non-negative values'			)
 return side_length**2


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if base < 0 or height < 0:
  raise ValueError('area_triangle() only accepts non-negative values'			)
 return (base * height) / 2


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if sidea < 0 or sidea < 0 or sidea < 0:
  raise ValueError('area_triangle_three_sides() only accepts non-negative values'			)
 elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea:
  raise ValueError('Given three sides do not form a triangle'			)
 __A  :		int       =			(sidea + sidea + sidea) / 2
 __A  :		List[Any]       =			sqrt(
     semi_perimeter
     * (semi_perimeter - sidea)
     * (semi_perimeter - sidea)
     * (semi_perimeter - sidea)			)
 return area


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if base < 0 or height < 0:
  raise ValueError('area_parallelogram() only accepts non-negative values'			)
 return base * height


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if basea < 0 or basea < 0 or height < 0:
  raise ValueError('area_trapezium() only accepts non-negative values'			)
 return 1 / 2 * (basea + basea) * height


def 			_lowercase       (				UpperCamelCase__       :					float			):
 if radius < 0:
  raise ValueError('area_circle() only accepts non-negative values'			)
 return pi * radius**2


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if radius_x < 0 or radius_y < 0:
  raise ValueError('area_ellipse() only accepts non-negative values'			)
 return pi * radius_x * radius_y


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					float			):
 if diagonal_a < 0 or diagonal_a < 0:
  raise ValueError('area_rhombus() only accepts non-negative values'			)
 return 1 / 2 * diagonal_a * diagonal_a


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					float			):
 if not isinstance(UpperCamelCase__,				UpperCamelCase__			) or sides < 3:
  raise ValueError(
      'area_reg_polygon() only accepts integers greater than or \
equal to three as number of sides'			)
 elif length < 0:
  raise ValueError(
      'area_reg_polygon() only accepts non-negative values as \
length of a side'			)
 return (sides * length**2) / (4 * tan(pi / sides			))
 return (sides * length**2) / (4 * tan(pi / sides			))


if __name__ == "__main__":
 import doctest

 doctest.testmod(verbose=True)  # verbose so we can see methods missing tests

 print('[DEMO] Areas of various geometric shapes: \n')
 print(f'''Rectangle: {area_rectangle(1_0, 2_0) = }''')
 print(f'''Square: {area_square(1_0) = }''')
 print(f'''Triangle: {area_triangle(1_0, 1_0) = }''')
 print(f'''Triangle: {area_triangle_three_sides(5, 1_2, 1_3) = }''')
 print(f'''Parallelogram: {area_parallelogram(1_0, 2_0) = }''')
 print(f'''Rhombus: {area_rhombus(1_0, 2_0) = }''')
 print(f'''Trapezium: {area_trapezium(1_0, 2_0, 3_0) = }''')
 print(f'''Circle: {area_circle(2_0) = }''')
 print(f'''Ellipse: {area_ellipse(1_0, 2_0) = }''')
 print('\nSurface Areas of various geometric shapes: \n')
 print(f'''Cube: {surface_area_cube(2_0) = }''')
 print(f'''Cuboid: {surface_area_cuboid(1_0, 2_0, 3_0) = }''')
 print(f'''Sphere: {surface_area_sphere(2_0) = }''')
 print(f'''Hemisphere: {surface_area_hemisphere(2_0) = }''')
 print(f'''Cone: {surface_area_cone(1_0, 2_0) = }''')
 print(f'''Conical Frustum: {surface_area_conical_frustum(1_0, 2_0, 3_0) = }''')
 print(f'''Cylinder: {surface_area_cylinder(1_0, 2_0) = }''')
 print(f'''Torus: {surface_area_torus(2_0, 1_0) = }''')
 print(f'''Equilateral Triangle: {area_reg_polygon(3, 1_0) = }''')
 print(f'''Square: {area_reg_polygon(4, 1_0) = }''')
 print(f'''Reqular Pentagon: {area_reg_polygon(5, 1_0) = }''')






