

'''simple docstring'''






import unittest

import numpy as np

from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
 from transformers.models.roberta.modeling_flax_roberta import (
     FlaxRobertaForCausalLM,
     FlaxRobertaForMaskedLM,
     FlaxRobertaForMultipleChoice,
     FlaxRobertaForQuestionAnswering,
     FlaxRobertaForSequenceClassification,
     FlaxRobertaForTokenClassification,
     FlaxRobertaModel,
 )






class     lowercase_			(unittest.TestCase   ):




  """simple docstring"""




  def __init__(   self     :  Union[str, Any]      ,lowercase__     :  Union[str, Any]      ,lowercase__     :  Dict=1_3      ,lowercase__     :  Any=7      ,lowercase__     :  Optional[Any]=True      ,lowercase__     :  Tuple=True      ,lowercase__     :  List[str]=True      ,lowercase__     :  Optional[int]=True      ,lowercase__     :  int=9_9      ,lowercase__     :  List[str]=3_2      ,lowercase__     :  Any=5      ,lowercase__     :  Union[str, Any]=4      ,lowercase__     :  Tuple=3_7      ,lowercase__     :  int="gelu"      ,lowercase__     :  Optional[int]=0.1      ,lowercase__     :  Union[str, Any]=0.1      ,lowercase__     :  Optional[int]=5_1_2      ,lowercase__     :  Union[str, Any]=1_6      ,lowercase__     :  Optional[Any]=2      ,lowercase__     :  Optional[int]=0.0_2      ,lowercase__     :  Union[str, Any]=4      ,):
   __lowercase													=				parent
   __lowercase													=				batch_size
   __lowercase													=				seq_length
   __lowercase													=				is_training
   __lowercase													=				use_attention_mask
   __lowercase													=				use_token_type_ids
   __lowercase													=				use_labels
   __lowercase													=				vocab_size
   __lowercase													=				hidden_size
   __lowercase													=				num_hidden_layers
   __lowercase													=				num_attention_heads
   __lowercase													=				intermediate_size
   __lowercase													=				hidden_act
   __lowercase													=				hidden_dropout_prob
   __lowercase													=				attention_probs_dropout_prob
   __lowercase													=				max_position_embeddings
   __lowercase													=				type_vocab_size
   __lowercase													=				type_sequence_label_size
   __lowercase													=				initializer_range
   __lowercase													=				num_choices






  def       SCREAMING_SNAKE_CASE   (   self     :  Dict    ):
   __lowercase													=				ids_tensor([self.batch_size, self.seq_length]      ,self.vocab_size    )

   __lowercase													=				None
   if self.use_attention_mask:
    __lowercase													=				random_attention_mask([self.batch_size, self.seq_length]    )

   __lowercase													=				None
   if self.use_token_type_ids:
    __lowercase													=				ids_tensor([self.batch_size, self.seq_length]      ,self.type_vocab_size    )

   __lowercase													=				RobertaConfig(
       vocab_size=self.vocab_size      ,hidden_size=self.hidden_size      ,num_hidden_layers=self.num_hidden_layers      ,num_attention_heads=self.num_attention_heads      ,intermediate_size=self.intermediate_size      ,hidden_act=self.hidden_act      ,hidden_dropout_prob=self.hidden_dropout_prob      ,attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,max_position_embeddings=self.max_position_embeddings      ,type_vocab_size=self.type_vocab_size      ,is_decoder=lowercase__      ,initializer_range=self.initializer_range      ,)

   return config, input_ids, token_type_ids, attention_mask






  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   __lowercase													=				self.prepare_config_and_inputs()
   __lowercase						,			__lowercase						,			__lowercase						,			__lowercase													=				config_and_inputs
   __lowercase													=				{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
   return config, inputs_dict






  def       SCREAMING_SNAKE_CASE   (   self     :  Any    ):
   __lowercase													=				self.prepare_config_and_inputs()
   __lowercase						,			__lowercase						,			__lowercase						,			__lowercase													=				config_and_inputs

   __lowercase													=				True
   __lowercase													=				floats_tensor([self.batch_size, self.seq_length, self.hidden_size]    )
   __lowercase													=				ids_tensor([self.batch_size, self.seq_length]      ,vocab_size=2    )

   return (
       config,
       input_ids,
       token_type_ids,
       encoder_hidden_states,
       encoder_attention_mask,
   )






@require_flax
class     lowercase_			(lowerCamelCase__       , unittest.TestCase   ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						int           =    True

  SCREAMING_SNAKE_CASE					:						Dict           =    (
      (
          FlaxRobertaModel,
          FlaxRobertaForCausalLM,
          FlaxRobertaForMaskedLM,
          FlaxRobertaForSequenceClassification,
          FlaxRobertaForTokenClassification,
          FlaxRobertaForMultipleChoice,
          FlaxRobertaForQuestionAnswering,
      )
      if is_flax_available()
      else ()
  )






  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   __lowercase													=				FlaxRobertaModelTester(self    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  int    ):
   for model_class_name in self.all_model_classes:
    __lowercase													=				model_class_name.from_pretrained('''roberta-base'''      ,from_pt=lowercase__    )
    __lowercase													=				model(np.ones((1, 1)    )    )
    self.assertIsNotNone(lowercase__    )




'''simple docstring'''






import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
 import tensorflow as tf

if is_keras_nlp_available():
 from transformers.models.gpta import TFGPTaTokenizer


lowerCAmelCase__      		=			['''gpt2''']
lowerCAmelCase__      		=			'''gpt2'''

if is_tf_available():






 class     lowercase_			(tf.Module   ):




   """simple docstring"""




   def __init__(   self     :  List[str]      ,lowercase__     :  Tuple    ):
    super().__init__()
    __lowercase													=				tokenizer
    __lowercase													=				AutoConfig.from_pretrained(lowercase__    )
    __lowercase													=				TFGPTaLMHeadModel.from_config(lowercase__    )






   @tf.function(input_signature=(tf.TensorSpec((None,)      ,tf.string      ,name='''text'''    ),)    )
   def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]      ,lowercase__     :  Dict    ):
    __lowercase													=				self.tokenizer(lowercase__    )
    __lowercase													=				tokenized['''input_ids'''].to_tensor()

    __lowercase													=				tf.cast(input_ids_dense > 0      ,tf.intaa    )
    # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

    __lowercase													=				self.model(input_ids=lowercase__      ,attention_mask=lowercase__    )['''logits''']

    return outputs






@require_tf
@require_keras_nlp
class     lowercase_			(unittest.TestCase   ):




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  List[Any]    ):
   super().setUp()

   __lowercase													=				[GPTaTokenizer.from_pretrained(lowercase__    ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
   __lowercase													=				[TFGPTaTokenizer.from_pretrained(lowercase__    ) for checkpoint in TOKENIZER_CHECKPOINTS]
   assert len(self.tokenizers    ) == len(self.tf_tokenizers    )

   __lowercase													=				[
       '''This is a straightforward English test sentence.''',
       '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
       '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
       '''And some much more rare Chinese: 齉 堃 齉堃''',
       '''Je vais aussi écrire en français pour tester les accents''',
       '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
   ]
   __lowercase													=				list(zip(self.test_sentences      ,self.test_sentences[::-1]    )    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   for tokenizer, tf_tokenizer in zip(self.tokenizers      ,self.tf_tokenizers    ):
    for test_inputs in self.test_sentences:
     __lowercase													=				tokenizer([test_inputs]      ,return_tensors='''tf'''    )
     __lowercase													=				tf_tokenizer([test_inputs]    )

     for key in python_outputs.keys():
      # convert them to numpy to avoid messing with ragged tensors
      __lowercase													=				python_outputs[key].numpy()
      __lowercase													=				tf_outputs[key].numpy()

      self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape    )    )
      self.assertTrue(tf.reduce_all(tf.cast(lowercase__      ,tf.intaa    ) == tf_outputs_values    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   for tf_tokenizer in self.tf_tokenizers:
    __lowercase													=				tf.function(lowercase__    )
    for test_inputs in self.test_sentences:
     __lowercase													=				tf.constant(lowercase__    )
     __lowercase													=				compiled_tokenizer(lowercase__    )
     __lowercase													=				tf_tokenizer(lowercase__    )

     for key in eager_outputs.keys():
      self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   for tf_tokenizer in self.tf_tokenizers:
    __lowercase													=				ModelToSave(tokenizer=lowercase__    )
    __lowercase													=				tf.convert_to_tensor([self.test_sentences[0]]    )
    __lowercase													=				model.serving(lowercase__    )  # Build model with some sample inputs
    with TemporaryDirectory() as tempdir:
     __lowercase													=				Path(lowercase__    ) / '''saved.model'''
     tf.saved_model.save(lowercase__      ,lowercase__      ,signatures={'''serving_default''': model.serving}    )
     __lowercase													=				tf.saved_model.load(lowercase__    )
    __lowercase													=				loaded_model.signatures['''serving_default'''](lowercase__    )['''output_0''']
    # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
    self.assertTrue(tf.reduce_all(out == loaded_output    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   for tf_tokenizer in self.tf_tokenizers:
    __lowercase													=				tf.convert_to_tensor([self.test_sentences[0]]    )
    __lowercase													=				tf_tokenizer(lowercase__    )  # Build model with some sample inputs

    __lowercase													=				tf_tokenizer.get_config()
    __lowercase													=				TFGPTaTokenizer.from_config(lowercase__    )
    __lowercase													=				model_from_config(lowercase__    )

    for key in from_config_output.keys():
     self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]    )    )






  @slow
  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   for tf_tokenizer in self.tf_tokenizers:
    # for the test to run
    __lowercase													=				1_2_3_1_2_3

    for max_length in [3, 5, 1_0_2_4]:
     __lowercase													=				tf.convert_to_tensor([self.test_sentences[0]]    )
     __lowercase													=				tf_tokenizer(lowercase__      ,max_length=lowercase__    )

     __lowercase													=				out['''input_ids'''].numpy().shape[1]

     assert out_length == max_length

