
'''simple docstring'''
from __future__ import annotations

import unittest

import numpy as np

from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow

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


if is_tf_available():
  import tensorflow as tf

  from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel

def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE=None,		__SCREAMING_SNAKE_CASE=None       ):
    """simple docstring"""






    if attention_mask is None:
        snake_case_ :    str     			=						tf.cast(tf.math.not_equal(__SCREAMING_SNAKE_CASE,		config.pad_token_id       ),		tf.inta       )
    return {"input_ids": input_ids, "attention_mask": attention_mask}






@require_tf
class    UpperCAmelCase_				:
 UpperCAmelCase_		    =						OPTConfig
 UpperCAmelCase_		    =						{}
 UpperCAmelCase_		    =						"""gelu"""





 def __init__(    self ,       lowercase_ ,       lowercase_=13 ,       lowercase_=7 ,       lowercase_=True ,       lowercase_=False ,       lowercase_=99 ,       lowercase_=16 ,       lowercase_=2 ,       lowercase_=4 ,       lowercase_=4 ,       lowercase_="gelu" ,       lowercase_=0.1 ,       lowercase_=0.1 ,       lowercase_=20 ,       lowercase_=2 ,       lowercase_=1 ,       lowercase_=0 ,       lowercase_=16 ,       lowercase_=16 ,       ):
     snake_case_ :    Optional[int]     			=						parent
     snake_case_ :    Optional[Any]     			=						batch_size
     snake_case_ :    Optional[int]     			=						seq_length
     snake_case_ :    List[str]     			=						is_training
     snake_case_ :    List[str]     			=						use_labels
     snake_case_ :    str     			=						vocab_size
     snake_case_ :    Union[str, Any]     			=						hidden_size
     snake_case_ :    Union[str, Any]     			=						num_hidden_layers
     snake_case_ :    List[Any]     			=						num_attention_heads
     snake_case_ :    Optional[int]     			=						intermediate_size
     snake_case_ :    Optional[Any]     			=						hidden_act
     snake_case_ :    List[Any]     			=						hidden_dropout_prob
     snake_case_ :    List[Any]     			=						attention_probs_dropout_prob
     snake_case_ :    str     			=						max_position_embeddings
     snake_case_ :    Union[str, Any]     			=						eos_token_id
     snake_case_ :    Tuple     			=						pad_token_id
     snake_case_ :    Tuple     			=						bos_token_id
     snake_case_ :    List[str]     			=						embed_dim
     snake_case_ :    int     			=						word_embed_proj_dim
     snake_case_ :    List[Any]     			=						False





 def        snake_case__		(    self):
     snake_case_ :    List[Any]     			=						ids_tensor([self.batch_size, self.seq_length - 1] ,       self.vocab_size)
     snake_case_ :    List[Any]     			=						tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) ,       1)
     snake_case_ :    Any     			=						tf.concat([input_ids, eos_tensor] ,       axis=1)

     snake_case_ :    List[Any]     			=						self.config_cls(
         vocab_size=self.vocab_size ,       hidden_size=self.hidden_size ,       num_hidden_layers=self.num_hidden_layers ,       num_attention_heads=self.num_attention_heads ,       ffn_dim=self.intermediate_size ,       dropout=self.hidden_dropout_prob ,       attention_dropout=self.attention_probs_dropout_prob ,       max_position_embeddings=self.max_position_embeddings ,       eos_token_id=self.eos_token_id ,       bos_token_id=self.bos_token_id ,       pad_token_id=self.pad_token_id ,       embed_dim=self.embed_dim ,       word_embed_proj_dim=self.word_embed_proj_dim ,       is_encoder_decoder=lowercase_ ,       **self.config_updates ,       )
     snake_case_ :    Union[str, Any]     			=						prepare_opt_inputs_dict(lowercase_ ,       lowercase_)
     return config, inputs_dict





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_):
     snake_case_ :    Any     			=						TFOPTModel(config=lowercase_)
     snake_case_ :    List[Any]     			=						inputs_dict["input_ids"]

     snake_case_ :    Any     			=						input_ids[:1, :]
     snake_case_ :    int     			=						inputs_dict["attention_mask"][:1, :]
     snake_case_ :    List[Any]     			=						1

     # first forward pass
     snake_case_ :    Dict     			=						model(lowercase_ ,       attention_mask=lowercase_ ,       use_cache=lowercase_)

     snake_case_			, snake_case_ :    Optional[Any]     			=						outputs.to_tuple()

     # create hypothetical next token and extent to next_input_ids
     snake_case_ :    Union[str, Any]     			=						ids_tensor((self.batch_size, 3) ,       config.vocab_size)
     snake_case_ :    str     			=						tf.cast(ids_tensor((self.batch_size, 3) ,       2) ,       tf.inta)

     # append to next input_ids and
     snake_case_ :    int     			=						tf.concat([input_ids, next_tokens] ,       axis=-1)
     snake_case_ :    List[str]     			=						tf.concat([attention_mask, next_attn_mask] ,       axis=-1)

     snake_case_ :    Dict     			=						model(lowercase_ ,       attention_mask=lowercase_)[0]
     snake_case_ :    str     			=						model(lowercase_ ,       attention_mask=lowercase_ ,       past_key_values=lowercase_)[0]

     self.parent.assertEqual(next_tokens.shape[1] ,       output_from_past.shape[1])

     # select random slice
     snake_case_ :    Optional[int]     			=						int(ids_tensor((1,) ,       output_from_past.shape[-1]))
     snake_case_ :    int     			=						output_from_no_past[:, -3:, random_slice_idx]
     snake_case_ :    List[Any]     			=						output_from_past[:, :, random_slice_idx]

     # test that outputs are equal for slice
     tf.debugging.assert_near(lowercase_ ,       lowercase_ ,       rtol=1E-3)






@require_tf
class    UpperCAmelCase_				(	snake_case__    ,						snake_case__    ,						unittest.TestCase					):
 UpperCAmelCase_		    =						(TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
 UpperCAmelCase_		    =						(TFOPTForCausalLM,) if is_tf_available() else ()
 UpperCAmelCase_		    =						(
     {"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {}
 )
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						1_0





 def        snake_case__		(    self):
     snake_case_ :    int     			=						TFOPTModelTester(self)
     snake_case_ :    List[Any]     			=						ConfigTester(self ,       config_class=lowercase_)





 def        snake_case__		(    self):
     self.config_tester.run_common_tests()





 def        snake_case__		(    self):
     snake_case_ :    Optional[Any]     			=						self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_decoder_model_past_large_inputs(*lowercase_)





 def        snake_case__		(    self):
     snake_case_			, snake_case_ :    int     			=						self.model_tester.prepare_config_and_inputs_for_common()

     def _get_word_embedding_weight(lowercase_ ,       lowercase_):
         if hasattr(lowercase_ ,       "weight"):
             return embedding_layer.weight
         else:
             # Here we build the word embeddings weights if not exists.
             # And then we retry to get the attribute once built.
             model.build()
             if hasattr(lowercase_ ,       "weight"):
                 return embedding_layer.weight
             else:
                 return None

     for model_class in self.all_model_classes:
         for size in [config.vocab_size - 10, config.vocab_size + 10]:
             # build the embeddings
             snake_case_ :    List[str]     			=						model_class(config=lowercase_)
             snake_case_ :    Union[str, Any]     			=						_get_word_embedding_weight(lowercase_ ,       model.get_input_embeddings())
             snake_case_ :    Any     			=						_get_word_embedding_weight(lowercase_ ,       model.get_output_embeddings())

             # reshape the embeddings
             model.resize_token_embeddings(lowercase_)
             snake_case_ :    Union[str, Any]     			=						_get_word_embedding_weight(lowercase_ ,       model.get_input_embeddings())
             snake_case_ :    Tuple     			=						_get_word_embedding_weight(lowercase_ ,       model.get_output_embeddings())

             # check that the resized embeddings size matches the desired size.
             snake_case_ :    Optional[Any]     			=						size if size is not None else config.vocab_size

             self.assertEqual(new_input_embeddings.shape[0] ,       lowercase_)

             # check that weights remain the same after resizing
             snake_case_ :    Any     			=						True
             for pa, pa in zip(old_input_embeddings.value() ,       new_input_embeddings.value()):
                 if tf.math.reduce_sum(tf.math.abs(pa - pa)) > 0:
                     snake_case_ :    Optional[int]     			=						False
             self.assertTrue(lowercase_)

             if old_output_embeddings is not None and new_output_embeddings is not None:
                 self.assertEqual(new_output_embeddings.shape[0] ,       lowercase_)

                 snake_case_ :    List[Any]     			=						True
                 for pa, pa in zip(old_output_embeddings.value() ,       new_output_embeddings.value()):
                     if tf.math.reduce_sum(tf.math.abs(pa - pa)) > 0:
                         snake_case_ :    Any     			=						False
                 self.assertTrue(lowercase_)


def 						UpperCamelCase_     (	__SCREAMING_SNAKE_CASE       ):
    """simple docstring"""






    return tf.constant(__SCREAMING_SNAKE_CASE,		dtype=tf.intaa       )






@require_tf
class    UpperCAmelCase_				(	unittest.TestCase					):
 UpperCAmelCase_		    =						9_9





 def        snake_case__		(    self):
     snake_case_ :    Optional[int]     			=						tf.ones((4, 1) ,       dtype=tf.intaa) * 2
     snake_case_ :    List[Any]     			=						tf.concat([ids_tensor((4, 6) ,       self.vocab_size - 3) + 3, eos_column_vector] ,       axis=1)
     snake_case_ :    Tuple     			=						input_ids.shape[0]
     snake_case_ :    List[str]     			=						OPTConfig(
         vocab_size=self.vocab_size ,       hidden_size=24 ,       num_hidden_layers=2 ,       num_attention_heads=2 ,       ffn_dim=32 ,       max_position_embeddings=48 ,       eos_token_id=2 ,       pad_token_id=1 ,       bos_token_id=0 ,       )
     return config, input_ids, batch_size






@require_sentencepiece
@require_tf
class    UpperCAmelCase_				(	unittest.TestCase					):





 @slow
 def        snake_case__		(    self):
     snake_case_ :    List[Any]     			=						TFOPTModel.from_pretrained("facebook/opt-350m")
     snake_case_ :    List[Any]     			=						_long_tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]])
     snake_case_ :    int     			=						tf.not_equal(lowercase_ ,       model.config.pad_token_id)
     with tf.GradientTape():
         snake_case_ :    Optional[Any]     			=						model(input_ids=lowercase_ ,       attention_mask=lowercase_).last_hidden_state
     snake_case_ :    Union[str, Any]     			=						(1, 11, 5_12)
     self.assertEqual(output.shape ,       lowercase_)
     snake_case_ :    Optional[int]     			=						tf.constant(
         [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]])
     self.assertTrue(np.allclose(output[:, :3, :3] ,       lowercase_ ,       atol=4E-3))

     snake_case_ :    Optional[int]     			=						tf.function(lowercase_ ,       jit_compile=lowercase_)
     snake_case_ :    Dict     			=						xla_generate(lowercase_ ,       lowercase_)[0]
     self.assertTrue(np.allclose(output[:, :3, :3] ,       lowercase_ ,       atol=4E-2))






@require_tf
@slow
class    UpperCAmelCase_				(	unittest.TestCase					):





 def        snake_case__		(    self):
     super().setUp()
     snake_case_ :    Tuple     			=						"facebook/opt-350m"





 def        snake_case__		(    self):
     snake_case_ :    Tuple     			=						TFOPTForCausalLM.from_pretrained(self.path_model)
     snake_case_ :    str     			=						GPTaTokenizer.from_pretrained(self.path_model)

     snake_case_ :    Optional[Any]     			=						[
         "Today is a beautiful day and I want to",
         "In the city of",
         "Paris is the capital of France and",
         "Computers and mobile phones have taken",
     ]
     # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
     snake_case_ :    Union[str, Any]     			=						tokenizer(lowercase_ ,       return_tensors="tf" ,       padding=lowercase_ ,       add_special_tokens=lowercase_)
     snake_case_ :    List[Any]     			=						tf.math.reduce_mean(model(inputs.input_ids ,       attention_mask=inputs.attention_mask)[0] ,       axis=-1)
     snake_case_ :    List[Any]     			=						tf.constant(
         [
             [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670],
             [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822],
             [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703],
             [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477],
         ])
     self.assertTrue(np.allclose(lowercase_ ,       lowercase_ ,       atol=1E-4))

     snake_case_ :    Optional[int]     			=						tf.function(lowercase_ ,       jit_compile=lowercase_)
     snake_case_ :    List[str]     			=						tf.math.reduce_mean(xla_generate(inputs.input_ids ,       attention_mask=inputs.attention_mask)[0] ,       axis=-1)
     self.assertTrue(np.allclose(lowercase_ ,       lowercase_ ,       atol=1E-4))






@require_tf
@slow
class    UpperCAmelCase_				(	unittest.TestCase					):





 @property
 def        snake_case__		(    self):
     return [
         "Today is a beautiful day and I want",
         "In the city of",
         "Paris is the capital of France and",
         "Computers and mobile phones have taken",
     ]





 def        snake_case__		(    self):
     snake_case_ :    int     			=						"facebook/opt-125m"

     snake_case_ :    Union[str, Any]     			=						[
         "Today is a beautiful day and I want to",
         "In the city of New York, the city",
         "Paris is the capital of France and the capital",
         "Computers and mobile phones have taken over the",
     ]

     snake_case_ :    Dict     			=						[]
     snake_case_ :    int     			=						GPTaTokenizer.from_pretrained(lowercase_)
     snake_case_ :    Optional[Any]     			=						TFOPTForCausalLM.from_pretrained(lowercase_)

     for prompt in self.prompts:
         snake_case_ :    str     			=						tokenizer(lowercase_ ,       return_tensors="tf").input_ids

         snake_case_ :    Optional[int]     			=						model.generate(lowercase_ ,       max_length=10)

         snake_case_ :    int     			=						tokenizer.batch_decode(lowercase_ ,       skip_special_tokens=lowercase_)
         predicted_outputs += generated_string

     self.assertListEqual(lowercase_ ,       lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    List[Any]     			=						"facebook/opt-350m"

     snake_case_ :    Tuple     			=						GPTaTokenizer.from_pretrained(lowercase_)
     snake_case_ :    Union[str, Any]     			=						TFOPTForCausalLM.from_pretrained(lowercase_)

     snake_case_ :    Union[str, Any]     			=						"left"

     # use different length sentences to test batching
     snake_case_ :    Tuple     			=						[
         "Hello, my dog is a little",
         "Today, I",
     ]

     snake_case_ :    Union[str, Any]     			=						tokenizer(lowercase_ ,       return_tensors="tf" ,       padding=lowercase_)
     snake_case_ :    Optional[Any]     			=						inputs["input_ids"]

     snake_case_ :    Optional[Any]     			=						model.generate(input_ids=lowercase_ ,       attention_mask=inputs["attention_mask"])

     snake_case_ :    List[str]     			=						tokenizer(sentences[0] ,       return_tensors="tf").input_ids
     snake_case_ :    Any     			=						model.generate(input_ids=lowercase_)

     snake_case_ :    int     			=						inputs_non_padded.shape[-1] - tf.math.reduce_sum(
         tf.cast(inputs["attention_mask"][-1] ,       tf.intaa))
     snake_case_ :    Dict     			=						tokenizer(sentences[1] ,       return_tensors="tf").input_ids
     snake_case_ :    Any     			=						model.generate(input_ids=lowercase_ ,       max_length=model.config.max_length - num_paddings)

     snake_case_ :    str     			=						tokenizer.batch_decode(lowercase_ ,       skip_special_tokens=lowercase_)
     snake_case_ :    str     			=						tokenizer.decode(output_non_padded[0] ,       skip_special_tokens=lowercase_)
     snake_case_ :    Union[str, Any]     			=						tokenizer.decode(output_padded[0] ,       skip_special_tokens=lowercase_)

     snake_case_ :    Union[str, Any]     			=						[
         "Hello, my dog is a little bit of a dork.\nI'm a little bit",
         "Today, I was in the middle of a conversation with a friend about the",
     ]
     self.assertListEqual(lowercase_ ,       lowercase_)
     self.assertListEqual(lowercase_ ,       [non_padded_sentence, padded_sentence])





 def        snake_case__		(    self):
     snake_case_ :    int     			=						"facebook/opt-350m"

     snake_case_ :    Optional[Any]     			=						[
         "Today is a beautiful day and I want to",
         "In the city of San Francisco, the city",
         "Paris is the capital of France and the capital",
         "Computers and mobile phones have taken over the",
     ]

     snake_case_ :    Any     			=						[]
     snake_case_ :    Dict     			=						GPTaTokenizer.from_pretrained(lowercase_)
     snake_case_ :    int     			=						TFOPTForCausalLM.from_pretrained(lowercase_)

     for prompt in self.prompts:
         snake_case_ :    List[Any]     			=						tokenizer(lowercase_ ,       return_tensors="tf").input_ids

         snake_case_ :    List[str]     			=						model.generate(lowercase_ ,       max_length=10)

         snake_case_ :    Dict     			=						tokenizer.batch_decode(lowercase_ ,       skip_special_tokens=lowercase_)
         predicted_outputs += generated_string

     self.assertListEqual(lowercase_ ,       lowercase_)






'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
  from ...onnx.config import PatchingSpec
  from ...tokenization_utils_base import PreTrainedTokenizerBase


a_											=						logging.get_logger(__name__)

a_											=						{
    "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json",
    "allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json",
    "allenai/longformer-large-4096-finetuned-triviaqa": (
        "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"
    ),
    "allenai/longformer-base-4096-extra.pos.embd.only": (
        "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"
    ),
    "allenai/longformer-large-4096-extra.pos.embd.only": (
        "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"
    ),
}






class    UpperCAmelCase_				(	snake_case__					):
 UpperCAmelCase_		    =						"""longformer"""





 def __init__(    self ,       lowercase_ = 5_12 ,       lowercase_ = 2 ,       lowercase_ = 1 ,       lowercase_ = 0 ,       lowercase_ = 2 ,       lowercase_ = 3_05_22 ,       lowercase_ = 7_68 ,       lowercase_ = 12 ,       lowercase_ = 12 ,       lowercase_ = 30_72 ,       lowercase_ = "gelu" ,       lowercase_ = 0.1 ,       lowercase_ = 0.1 ,       lowercase_ = 5_12 ,       lowercase_ = 2 ,       lowercase_ = 0.02 ,       lowercase_ = 1E-12 ,       lowercase_ = False ,       **lowercase_ ,       ):
     super().__init__(pad_token_id=lowercase_ ,       **lowercase_)

     snake_case_ :    Dict     			=						attention_window
     snake_case_ :    Tuple     			=						sep_token_id
     snake_case_ :    Optional[Any]     			=						bos_token_id
     snake_case_ :    str     			=						eos_token_id
     snake_case_ :    Optional[int]     			=						vocab_size
     snake_case_ :    Dict     			=						hidden_size
     snake_case_ :    Optional[Any]     			=						num_hidden_layers
     snake_case_ :    int     			=						num_attention_heads
     snake_case_ :    Union[str, Any]     			=						hidden_act
     snake_case_ :    Union[str, Any]     			=						intermediate_size
     snake_case_ :    Union[str, Any]     			=						hidden_dropout_prob
     snake_case_ :    Optional[Any]     			=						attention_probs_dropout_prob
     snake_case_ :    List[str]     			=						max_position_embeddings
     snake_case_ :    str     			=						type_vocab_size
     snake_case_ :    Tuple     			=						initializer_range
     snake_case_ :    List[str]     			=						layer_norm_eps
     snake_case_ :    Tuple     			=						onnx_export






class    UpperCAmelCase_				(	snake_case__					):





 def __init__(    self ,       lowercase_ ,       lowercase_ = "default" ,       lowercase_ = None):
     super().__init__(lowercase_ ,       lowercase_ ,       lowercase_)
     snake_case_ :    Dict     			=						True





 @property
 def        snake_case__		(    self):
     if self.task == "multiple-choice":
         snake_case_ :    Tuple     			=						{0: "batch", 1: "choice", 2: "sequence"}
     else:
         snake_case_ :    int     			=						{0: "batch", 1: "sequence"}
     return OrderedDict(
         [
             ("input_ids", dynamic_axis),
             ("attention_mask", dynamic_axis),
             ("global_attention_mask", dynamic_axis),
         ])





 @property
 def        snake_case__		(    self):
     snake_case_ :    Union[str, Any]     			=						super().outputs
     if self.task == "default":
         snake_case_ :    str     			=						{0: "batch"}
     return outputs





 @property
 def        snake_case__		(    self):
     return 1E-4





 @property
 def        snake_case__		(    self):
     # needs to be >= 14 to support tril operator
     return max(super().default_onnx_opset ,       14)





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ = -1 ,       lowercase_ = -1 ,       lowercase_ = False ,       lowercase_ = None ,       ):
     snake_case_ :    Optional[Any]     			=						super().generate_dummy_inputs(
         preprocessor=lowercase_ ,       batch_size=lowercase_ ,       seq_length=lowercase_ ,       is_pair=lowercase_ ,       framework=lowercase_)
     import torch

     # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
     # makes the export fail randomly
     snake_case_ :    Any     			=						torch.zeros_like(inputs["input_ids"])
     # make every second token global
     snake_case_ :    Tuple     			=						1

     return inputs




