


'''simple docstring'''







import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
       import os

       import jax.numpy as jnp
       from jax import jit

       from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
       from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

       lowerCAmelCase     :  Union[str, Any]											=    """0.12"""  # assumed parallelism: 8


if is_torch_available():
       import torch






def       lowercase					(_A ,    _A ,    _A=None       ):







       """simple docstring"""







       if rng is None:
              _lowerCAmelCase     :				str       =							random.Random()

       _lowerCAmelCase     :				List[Any]       =							1
       for dim in shape:
              total_dims *= dim

       _lowerCAmelCase     :				Tuple       =							[]
       for _ in range(_A       ):
              values.append(rng.randint(0 ,    vocab_size - 1       )       )

       _lowerCAmelCase     :				int       =							np.array(_A ,    dtype=jnp.intaa       ).reshape(_A       )

       return output






def       lowercase					(_A ,    _A=None       ):







       """simple docstring"""







       _lowerCAmelCase     :				Optional[int]       =							ids_tensor(_A ,    vocab_size=2 ,    rng=_A       )
       # make sure that at least one token is attended to for each batch
       _lowerCAmelCase     :				Optional[Any]       =							1
       return attn_mask
@require_flax
class 						UpperCamelCase__       :



     """simple docstring"""






     __magic_name__           =     None
     __magic_name__           =     ()







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase     :				List[str]       =							self.model_tester.prepare_config_and_inputs_for_common()

            # cut to half length & take max batch_size 3
            _lowerCAmelCase     :				int       =							2
            _lowerCAmelCase     :				List[str]       =							inputs['input_ids'].shape[-1] // 2
            _lowerCAmelCase     :				Optional[Any]       =							inputs['input_ids'][:max_batch_size, :sequence_length]

            _lowerCAmelCase     :				Optional[int]       =							jnp.ones_like(snake_case__ )
            _lowerCAmelCase     :				List[Any]       =							attention_mask[:max_batch_size, :sequence_length]

            # generate max 5 tokens
            _lowerCAmelCase     :				Tuple       =							input_ids.shape[-1] + 5
            if config.eos_token_id is not None and config.pad_token_id is None:
                   # hack to allow generate for models such as GPT2 as is done in `generate()`
                   _lowerCAmelCase     :				Any       =							config.eos_token_id
            return config, input_ids, attention_mask, max_length







     @is_pt_flax_cross_test
     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Any       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				List[Any]       =							False
            _lowerCAmelCase     :				Optional[int]       =							max_length
            _lowerCAmelCase     :				List[str]       =							0

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Dict       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				Optional[Any]       =							model_class.__name__[4:]  # Skip the "Flax" at the beginning
                   _lowerCAmelCase     :				Tuple       =							getattr(snake_case__   ,						snake_case__ )
                   _lowerCAmelCase     :				Optional[int]       =							pt_model_class(snake_case__ ).eval()
                   _lowerCAmelCase     :				int       =							load_flax_weights_in_pytorch_model(snake_case__   ,						flax_model.params )

                   _lowerCAmelCase     :				int       =							flax_model.generate(snake_case__ ).sequences
                   _lowerCAmelCase     :				str       =							pt_model.generate(torch.tensor(snake_case__   ,						dtype=torch.long ) )

                   if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
                          _lowerCAmelCase     :				List[Any]       =							flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

                   self.assertListEqual(pt_generation_outputs.numpy().tolist()   ,						flax_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Dict       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				Optional[Any]       =							False
            _lowerCAmelCase     :				str       =							max_length

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[Any]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				List[Any]       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				int       =							jit(model.generate )
                   _lowerCAmelCase     :				Optional[int]       =							jit_generate(snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				str       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				Union[str, Any]       =							True
            _lowerCAmelCase     :				int       =							max_length

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[Any]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				List[str]       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				Tuple       =							jit(model.generate )
                   _lowerCAmelCase     :				int       =							jit_generate(snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Dict       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				Dict       =							False
            _lowerCAmelCase     :				str       =							max_length
            _lowerCAmelCase     :				Dict       =							2

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[int]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				Optional[Any]       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				Optional[Any]       =							jit(model.generate )
                   _lowerCAmelCase     :				List[str]       =							jit_generate(snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				List[str]       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				Any       =							False
            _lowerCAmelCase     :				Any       =							max_length
            _lowerCAmelCase     :				Any       =							2
            _lowerCAmelCase     :				List[Any]       =							2

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Tuple       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				str       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[0]   ,						input_ids.shape[0] * config.num_return_sequences )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				str       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				List[Any]       =							True
            _lowerCAmelCase     :				int       =							max_length
            _lowerCAmelCase     :				List[str]       =							0.8
            _lowerCAmelCase     :				Union[str, Any]       =							10
            _lowerCAmelCase     :				Any       =							0.3
            _lowerCAmelCase     :				List[Any]       =							1
            _lowerCAmelCase     :				int       =							8
            _lowerCAmelCase     :				List[Any]       =							9

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[int]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				str       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				str       =							jit(model.generate )
                   _lowerCAmelCase     :				str       =							jit_generate(snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Union[str, Any]       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				Dict       =							max_length
            _lowerCAmelCase     :				str       =							1
            _lowerCAmelCase     :				Union[str, Any]       =							8
            _lowerCAmelCase     :				int       =							9

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				str       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				List[Any]       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				List[str]       =							jit(model.generate )
                   _lowerCAmelCase     :				Optional[Any]       =							jit_generate(snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Tuple       =							self._get_input_ids_and_config()
            _lowerCAmelCase     :				str       =							max_length
            _lowerCAmelCase     :				str       =							2
            _lowerCAmelCase     :				str       =							1
            _lowerCAmelCase     :				List[str]       =							8
            _lowerCAmelCase     :				Union[str, Any]       =							9

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Tuple       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				int       =							model.generate(snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				Dict       =							jit(model.generate )
                   _lowerCAmelCase     :				Union[str, Any]       =							jit_generate(snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Any       =							self._get_input_ids_and_config()

            # pad attention mask on the left
            _lowerCAmelCase     :				Tuple       =							attention_mask.at[(0, 0)].set(0 )

            _lowerCAmelCase     :				Dict       =							False
            _lowerCAmelCase     :				Tuple       =							max_length

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[Any]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				Dict       =							model.generate(snake_case__   ,						attention_mask=snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				List[str]       =							jit(model.generate )
                   _lowerCAmelCase     :				List[Any]       =							jit_generate(snake_case__   ,						attention_mask=snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				List[Any]       =							self._get_input_ids_and_config()

            # pad attention mask on the left
            _lowerCAmelCase     :				List[Any]       =							attention_mask.at[(0, 0)].set(0 )

            _lowerCAmelCase     :				Union[str, Any]       =							True
            _lowerCAmelCase     :				Dict       =							max_length

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[int]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				List[Any]       =							model.generate(snake_case__   ,						attention_mask=snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				Dict       =							jit(model.generate )
                   _lowerCAmelCase     :				List[str]       =							jit_generate(snake_case__   ,						attention_mask=snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Optional[int]       =							self._get_input_ids_and_config()

            # pad attention mask on the left
            _lowerCAmelCase     :				List[str]       =							attention_mask.at[(0, 0)].set(0 )

            _lowerCAmelCase     :				Optional[Any]       =							2
            _lowerCAmelCase     :				Dict       =							max_length

            for model_class in self.all_generative_model_classes:
                   _lowerCAmelCase     :				Optional[int]       =							model_class(snake_case__ )

                   _lowerCAmelCase     :				Union[str, Any]       =							model.generate(snake_case__   ,						attention_mask=snake_case__ ).sequences
                   self.assertEqual(generation_outputs.shape[-1]   ,						snake_case__ )

                   _lowerCAmelCase     :				str       =							jit(model.generate )
                   _lowerCAmelCase     :				int       =							jit_generate(snake_case__   ,						attention_mask=snake_case__ ).sequences

                   self.assertListEqual(generation_outputs.tolist()   ,						jit_generation_outputs.tolist() )
@require_flax
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							AutoTokenizer.from_pretrained('hf-internal-testing/tiny-bert' )
            _lowerCAmelCase     :				Optional[Any]       =							FlaxAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-bert-flax-only' )

            _lowerCAmelCase     :				Any       =							'Hello world'
            _lowerCAmelCase     :				Any       =							tokenizer(snake_case__   ,						return_tensors='np' ).input_ids

            # typos are quickly detected (the correct argument is `do_sample`)
            with self.assertRaisesRegex(snake_case__   ,						'do_samples' ):
                   model.generate(snake_case__   ,						do_samples=snake_case__ )

            # arbitrary arguments that will not be used anywhere are also not accepted
            with self.assertRaisesRegex(snake_case__   ,						'foo' ):
                   _lowerCAmelCase     :				int       =							{'foo': 'bar'}
                   model.generate(snake_case__   ,						**snake_case__ )





'''simple docstring'''







from math import pi, sqrt, tan






def       lowercase					(_A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A ,    _A       ):







       """simple docstring"""







       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					(_A       ):







       """simple docstring"""







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






def       lowercase					(_A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A       ):







       """simple docstring"""







       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					(_A ,    _A ,    _A       ):







       """simple docstring"""







       if radius_a < 0 or radius_a < 0 or height < 0:
              raise ValueError(
                  'surface_area_conical_frustum() only accepts non-negative values'       )
       _lowerCAmelCase     :				int       =							(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					(_A ,    _A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A       ):







       """simple docstring"""







       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(_A ,    2       ) * torus_radius * tube_radius






def       lowercase					(_A ,    _A       ):







       """simple docstring"""







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






def       lowercase					(_A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A ,    _A       ):







       """simple docstring"""







       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'       )
       _lowerCAmelCase     :				Tuple       =							(sidea + sidea + sidea) / 2
       _lowerCAmelCase     :				Dict       =							sqrt(
           semi_perimeter
           * (semi_perimeter - sidea)
           * (semi_perimeter - sidea)
           * (semi_perimeter - sidea)       )
       return area






def       lowercase					(_A ,    _A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A ,    _A       ):







       """simple docstring"""







       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					(_A       ):







       """simple docstring"""







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






def       lowercase					(_A ,    _A       ):







       """simple docstring"""







       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					(_A ,    _A       ):







       """simple docstring"""







       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					(_A ,    _A       ):







       """simple docstring"""







       if not isinstance(_A ,    _A       ) 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(10, 20) = }''')
       print(F'''Square: {area_square(10) = }''')
       print(F'''Triangle: {area_triangle(10, 10) = }''')
       print(F'''Triangle: {area_triangle_three_sides(5, 12, 13) = }''')
       print(F'''Parallelogram: {area_parallelogram(10, 20) = }''')
       print(F'''Rhombus: {area_rhombus(10, 20) = }''')
       print(F'''Trapezium: {area_trapezium(10, 20, 30) = }''')
       print(F'''Circle: {area_circle(20) = }''')
       print(F'''Ellipse: {area_ellipse(10, 20) = }''')
       print("""\nSurface Areas of various geometric shapes: \n""")
       print(F'''Cube: {surface_area_cube(20) = }''')
       print(F'''Cuboid: {surface_area_cuboid(10, 20, 30) = }''')
       print(F'''Sphere: {surface_area_sphere(20) = }''')
       print(F'''Hemisphere: {surface_area_hemisphere(20) = }''')
       print(F'''Cone: {surface_area_cone(10, 20) = }''')
       print(F'''Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }''')
       print(F'''Cylinder: {surface_area_cylinder(10, 20) = }''')
       print(F'''Torus: {surface_area_torus(20, 10) = }''')
       print(F'''Equilateral Triangle: {area_reg_polygon(3, 10) = }''')
       print(F'''Square: {area_reg_polygon(4, 10) = }''')
       print(F'''Reqular Pentagon: {area_reg_polygon(5, 10) = }''')

