



from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers.models.xglm.modeling_tf_xglm import (
          TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFXGLMForCausalLM,
          TFXGLMModel,
      )







@require_tf
class 	_snake_case							:






   '''simple docstring'''






   A__	:      Dict    =		XGLMConfig
   A__	:      int    =		{}
   A__	:      List[str]    =		"""gelu"""


   def __init__(  self:			Optional[Any]   ,lowerCamelCase_:			List[str]   ,lowerCamelCase_:			Optional[Any]=14   ,lowerCamelCase_:			Union[str, Any]=7   ,lowerCamelCase_:			Dict=True   ,lowerCamelCase_:			Any=True   ,lowerCamelCase_:			Any=True   ,lowerCamelCase_:			Dict=99   ,lowerCamelCase_:			Any=32   ,lowerCamelCase_:			Dict=2   ,lowerCamelCase_:			Dict=4   ,lowerCamelCase_:			Any=37   ,lowerCamelCase_:			Tuple="gelu"   ,lowerCamelCase_:			Tuple=0.1   ,lowerCamelCase_:			Union[str, Any]=0.1   ,lowerCamelCase_:			Dict=512   ,lowerCamelCase_:			Optional[int]=0.0_2   ,)     ->	List[str]:
       UpperCAmelCase_			:    List[Any]   						= parent
       UpperCAmelCase_			:    List[Any]   						= batch_size
       UpperCAmelCase_			:    Any   						= seq_length
       UpperCAmelCase_			:    List[Any]   						= is_training
       UpperCAmelCase_			:    int   						= use_input_mask
       UpperCAmelCase_			:    Union[str, Any]   						= use_labels
       UpperCAmelCase_			:    str   						= vocab_size
       UpperCAmelCase_			:    List[str]   						= d_model
       UpperCAmelCase_			:    Dict   						= num_hidden_layers
       UpperCAmelCase_			:    Tuple   						= num_attention_heads
       UpperCAmelCase_			:    Dict   						= ffn_dim
       UpperCAmelCase_			:    Any   						= activation_function
       UpperCAmelCase_			:    List[Any]   						= activation_dropout
       UpperCAmelCase_			:    Dict   						= attention_dropout
       UpperCAmelCase_			:    Optional[Any]   						= max_position_embeddings
       UpperCAmelCase_			:    Union[str, Any]   						= initializer_range
       UpperCAmelCase_			:    Dict   						= None
       UpperCAmelCase_			:    Any   						= 0
       UpperCAmelCase_			:    Optional[Any]   						= 2
       UpperCAmelCase_			:    List[Any]   						= 1


   def 	A__  (  self:			Any				)     ->	Tuple:
       return XGLMConfig.from_pretrained("""facebook/xglm-564M"""				)


   def 	A__  (  self:			int				)     ->	List[str]:
       UpperCAmelCase_			:    Dict   						= tf.clip_by_value(
           ids_tensor([self.batch_size, self.seq_length]   ,self.vocab_size				)   ,clip_value_min=0   ,clip_value_max=3				)

       UpperCAmelCase_			:    Optional[Any]   						= None
       if self.use_input_mask:
           UpperCAmelCase_			:    Any   						= random_attention_mask([self.batch_size, self.seq_length]				)

       UpperCAmelCase_			:    Tuple   						= self.get_config()

       UpperCAmelCase_			:    Optional[int]   						= floats_tensor([self.num_hidden_layers, self.num_attention_heads]   ,2				)

       return (
           config,
           input_ids,
           input_mask,
           head_mask,
       )


   def 	A__  (  self:			Dict				)     ->	Any:
       return XGLMConfig(
           vocab_size=self.vocab_size   ,d_model=self.hidden_size   ,num_layers=self.num_hidden_layers   ,attention_heads=self.num_attention_heads   ,ffn_dim=self.ffn_dim   ,activation_function=self.activation_function   ,activation_dropout=self.activation_dropout   ,attention_dropout=self.attention_dropout   ,max_position_embeddings=self.max_position_embeddings   ,initializer_range=self.initializer_range   ,use_cache=lowerCAmelCase__   ,bos_token_id=self.bos_token_id   ,eos_token_id=self.eos_token_id   ,pad_token_id=self.pad_token_id   ,return_dict=lowerCAmelCase__   ,)






   def 	A__  (  self:			Any				)     ->	List[Any]:
       UpperCAmelCase_			:    int   						= self.prepare_config_and_inputs()

       (
           (
           UpperCAmelCase_				
       )						,      (
           UpperCAmelCase_				
       )						,      (
           UpperCAmelCase_				
       )						,      (
           UpperCAmelCase_				
       )						,      				
       )			:    Any   						= config_and_inputs

       UpperCAmelCase_			:    List[Any]   						= {
           """input_ids""": input_ids,
           """head_mask""": head_mask,
       }

       return config, inputs_dict







@require_tf
class 	_snake_case							(			lowerCamelCase_      ,				lowerCamelCase_      ,				unittest.TestCase      ):






   '''simple docstring'''






   A__	:      List[str]    =		(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
   A__	:      Optional[Any]    =		(TFXGLMForCausalLM,) if is_tf_available() else ()
   A__	:      Union[str, Any]    =		(
       {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {}
   )
   A__	:      List[Any]    =		False
   A__	:      Any    =		False
   A__	:      Union[str, Any]    =		False


   def 	A__  (  self:			Union[str, Any]				)     ->	int:
       UpperCAmelCase_			:    List[Any]   						= TFXGLMModelTester(self				)
       UpperCAmelCase_			:    str   						= ConfigTester(self   ,config_class=lowerCAmelCase__   ,n_embd=37				)


   def 	A__  (  self:			Any				)     ->	List[Any]:
       self.config_tester.run_common_tests()


   @slow
   def 	A__  (  self:			int				)     ->	str:
       for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCAmelCase_			:    Optional[int]   						= TFXGLMModel.from_pretrained(lowerCAmelCase__				)
           self.assertIsNotNone(lowerCAmelCase__				)






   @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor."""				)
   def 	A__  (  self:			int				)     ->	Dict:
       super().test_resize_token_embeddings()







@require_tf
class 	_snake_case							(			unittest.TestCase      ):






   '''simple docstring'''






   @slow
   def 	A__  (  self:			int   ,lowerCamelCase_:			Optional[int]=True				)     ->	int:
       UpperCAmelCase_			:    Any   						= TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""				)
       UpperCAmelCase_			:    Optional[int]   						= tf.convert_to_tensor([[2, 268, 9865]]   ,dtype=tf.intaa				)  # The dog
       # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
       # fmt: off
       UpperCAmelCase_			:    Dict   						= [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581]
       # fmt: on
       UpperCAmelCase_			:    int   						= model.generate(lowerCAmelCase__   ,do_sample=lowerCAmelCase__   ,num_beams=1				)
       if verify_outputs:
           self.assertListEqual(output_ids[0].numpy().tolist()   ,lowerCAmelCase__				)


   @slow
   def 	A__  (  self:			Union[str, Any]				)     ->	Union[str, Any]:
       UpperCAmelCase_			:    Union[str, Any]   						= XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""				)
       UpperCAmelCase_			:    List[str]   						= TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""				)

       tf.random.set_seed(0				)
       UpperCAmelCase_			:    Union[str, Any]   						= tokenizer("""Today is a nice day and"""   ,return_tensors="""tf"""				)
       UpperCAmelCase_			:    Optional[int]   						= tokenized.input_ids
       # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
       with tf.device(""":/CPU:0"""				):
           UpperCAmelCase_			:    Union[str, Any]   						= model.generate(lowerCAmelCase__   ,do_sample=lowerCAmelCase__   ,seed=[7, 0]				)
       UpperCAmelCase_			:    List[str]   						= tokenizer.decode(output_ids[0]   ,skip_special_tokens=lowerCAmelCase__				)

       UpperCAmelCase_			:    int   						= (
           """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"""
       )
       self.assertEqual(lowerCAmelCase__   ,lowerCAmelCase__				)






   @slow
   def 	A__  (  self:			Optional[Any]				)     ->	List[Any]:
       UpperCAmelCase_			:    Optional[int]   						= TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""				)
       UpperCAmelCase_			:    List[str]   						= XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""				)

       UpperCAmelCase_			:    List[str]   						= """left"""

       # use different length sentences to test batching
       UpperCAmelCase_			:    Optional[Any]   						= [
           """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
           """left-padding, such as in batched generation. The output for the sequence below should be the same """
           """regardless of whether left padding is applied or not. When""",
           """Hello, my dog is a little""",
       ]

       UpperCAmelCase_			:    Tuple   						= tokenizer(lowerCAmelCase__   ,return_tensors="""tf"""   ,padding=lowerCAmelCase__				)
       UpperCAmelCase_			:    Any   						= inputs["""input_ids"""]

       UpperCAmelCase_			:    Union[str, Any]   						= model.generate(input_ids=lowerCAmelCase__   ,attention_mask=inputs["""attention_mask"""]   ,max_new_tokens=12				)

       UpperCAmelCase_			:    Optional[Any]   						= tokenizer(sentences[0]   ,return_tensors="""tf"""				).input_ids
       UpperCAmelCase_			:    Any   						= model.generate(input_ids=lowerCAmelCase__   ,max_new_tokens=12				)

       UpperCAmelCase_			:    int   						= tokenizer(sentences[1]   ,return_tensors="""tf"""				).input_ids
       UpperCAmelCase_			:    Optional[Any]   						= model.generate(input_ids=lowerCAmelCase__   ,max_new_tokens=12				)

       UpperCAmelCase_			:    Tuple   						= tokenizer.batch_decode(lowerCAmelCase__   ,skip_special_tokens=lowerCAmelCase__				)
       UpperCAmelCase_			:    Dict   						= tokenizer.decode(output_non_padded[0]   ,skip_special_tokens=lowerCAmelCase__				)
       UpperCAmelCase_			:    Optional[int]   						= tokenizer.decode(output_padded[0]   ,skip_special_tokens=lowerCAmelCase__				)

       UpperCAmelCase_			:    Optional[int]   						= [
           """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
           """left-padding, such as in batched generation. The output for the sequence below should be the same """
           """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """
           """a single""",
           """Hello, my dog is a little bit of a shy one, but he is very friendly""",
       ]
       self.assertListEqual(lowerCAmelCase__   ,lowerCAmelCase__				)
       self.assertListEqual(lowerCAmelCase__   ,[non_padded_sentence, padded_sentence]				)




"""simple docstring"""




from __future__ import annotations

from collections.abc import Callable


def     lowercase			(SCREAMING_SNAKE_CASE_		:				Callable[[int | float], int | float] ,			SCREAMING_SNAKE_CASE_		:				int | float ,			SCREAMING_SNAKE_CASE_		:				int | float ,			SCREAMING_SNAKE_CASE_		:				int = 1_00 ,			)   ->						float:
						SCREAMING_SNAKE_CASE													=					x_start
						SCREAMING_SNAKE_CASE													=					fnc(SCREAMING_SNAKE_CASE_  )
						SCREAMING_SNAKE_CASE													=					0.0
						for _ in range(SCREAMING_SNAKE_CASE_  ):
												# Approximates small segments of curve as linear and solve
												# for trapezoidal area
												SCREAMING_SNAKE_CASE													=					(x_end - x_start) / steps + xa
												SCREAMING_SNAKE_CASE													=					fnc(SCREAMING_SNAKE_CASE_  )
												area += abs(fxa + fxa  ) * (xa - xa) / 2
												# Increment step
												SCREAMING_SNAKE_CASE													=					xa
												SCREAMING_SNAKE_CASE													=					fxa
						return area


if __name__ == "__main__":


	def     lowercase			(SCREAMING_SNAKE_CASE_		:				Optional[int]  )   ->						Dict:
							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:''')
	__UpperCamelCase						=      10
	while i <= 100000:
		print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''')
		i *= 10


