





"""simple docstring"""





import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      XLMForMultipleChoice,
      XLMForQuestionAnswering,
      XLMForQuestionAnsweringSimple,
      XLMForSequenceClassification,
      XLMForTokenClassification,
      XLMModel,
      XLMWithLMHeadModel,
  )
  from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST






class    _lowerCAmelCase  :
       """simple docstring"""




       def __init__(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase=1_3       ,					__UpperCAmelCase=7       ,					__UpperCAmelCase=True       ,					__UpperCAmelCase=True       ,					__UpperCAmelCase=True       ,					__UpperCAmelCase=True       ,					__UpperCAmelCase=True       ,					__UpperCAmelCase=False       ,					__UpperCAmelCase=False       ,					__UpperCAmelCase=False       ,					__UpperCAmelCase=2       ,					__UpperCAmelCase=9_9       ,					__UpperCAmelCase=0       ,					__UpperCAmelCase=3_2       ,					__UpperCAmelCase=5       ,					__UpperCAmelCase=4       ,					__UpperCAmelCase=0.1       ,					__UpperCAmelCase=0.1       ,					__UpperCAmelCase=5_1_2       ,					__UpperCAmelCase=2       ,					__UpperCAmelCase=0.02       ,					__UpperCAmelCase=2       ,					__UpperCAmelCase=4       ,					__UpperCAmelCase="last"       ,					__UpperCAmelCase=True       ,					__UpperCAmelCase=None       ,					__UpperCAmelCase=0       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :List[Any]											=				parent
         lowerCAmelCase__     :Union[str, Any]											=				batch_size
         lowerCAmelCase__     :Any											=				seq_length
         lowerCAmelCase__     :Tuple											=				is_training
         lowerCAmelCase__     :Dict											=				use_input_lengths
         lowerCAmelCase__     :int											=				use_token_type_ids
         lowerCAmelCase__     :Tuple											=				use_labels
         lowerCAmelCase__     :List[Any]											=				gelu_activation
         lowerCAmelCase__     :List[str]											=				sinusoidal_embeddings
         lowerCAmelCase__     :Optional[Any]											=				causal
         lowerCAmelCase__     :Optional[Any]											=				asm
         lowerCAmelCase__     :Optional[Any]											=				n_langs
         lowerCAmelCase__     :List[str]											=				vocab_size
         lowerCAmelCase__     :Optional[int]											=				n_special
         lowerCAmelCase__     :List[str]											=				hidden_size
         lowerCAmelCase__     :int											=				num_hidden_layers
         lowerCAmelCase__     :str											=				num_attention_heads
         lowerCAmelCase__     :List[Any]											=				hidden_dropout_prob
         lowerCAmelCase__     :Tuple											=				attention_probs_dropout_prob
         lowerCAmelCase__     :Dict											=				max_position_embeddings
         lowerCAmelCase__     :Optional[int]											=				type_sequence_label_size
         lowerCAmelCase__     :Any											=				initializer_range
         lowerCAmelCase__     :Union[str, Any]											=				num_labels
         lowerCAmelCase__     :Union[str, Any]											=				num_choices
         lowerCAmelCase__     :Tuple											=				summary_type
         lowerCAmelCase__     :int											=				use_proj
         lowerCAmelCase__     :Any											=				scope
         lowerCAmelCase__     :List[Any]											=				bos_token_id






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Any											=				ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size )
         lowerCAmelCase__     :Tuple											=				random_attention_mask([self.batch_size, self.seq_length] )

         lowerCAmelCase__     :List[str]											=				None
         if self.use_input_lengths:
           lowerCAmelCase__     :Optional[int]											=				(
               ids_tensor([self.batch_size]       ,					vocab_size=2 ) + self.seq_length - 2
           )  # small variation of seq_length

         lowerCAmelCase__     :Optional[Any]											=				None
         if self.use_token_type_ids:
           lowerCAmelCase__     :Optional[int]											=				ids_tensor([self.batch_size, self.seq_length]       ,					self.n_langs )

         lowerCAmelCase__     :Union[str, Any]											=				None
         lowerCAmelCase__     :Union[str, Any]											=				None
         lowerCAmelCase__     :List[Any]											=				None
         if self.use_labels:
           lowerCAmelCase__     :str											=				ids_tensor([self.batch_size]       ,					self.type_sequence_label_size )
           lowerCAmelCase__     :List[Any]											=				ids_tensor([self.batch_size, self.seq_length]       ,					self.num_labels )
           lowerCAmelCase__     :Any											=				ids_tensor([self.batch_size]       ,					2 ).float()
           lowerCAmelCase__     :Tuple											=				ids_tensor([self.batch_size]       ,					self.num_choices )

         lowerCAmelCase__     :Tuple											=				self.get_config()

         return (
             config,
             input_ids,
             token_type_ids,
             input_lengths,
             sequence_labels,
             token_labels,
             is_impossible_labels,
             choice_labels,
             input_mask,
         )






       def 	snake_case		(       self ):



         '''simple docstring'''

         return XLMConfig(
             vocab_size=self.vocab_size       ,					n_special=self.n_special       ,					emb_dim=self.hidden_size       ,					n_layers=self.num_hidden_layers       ,					n_heads=self.num_attention_heads       ,					dropout=self.hidden_dropout_prob       ,					attention_dropout=self.attention_probs_dropout_prob       ,					gelu_activation=self.gelu_activation       ,					sinusoidal_embeddings=self.sinusoidal_embeddings       ,					asm=self.asm       ,					causal=self.causal       ,					n_langs=self.n_langs       ,					max_position_embeddings=self.max_position_embeddings       ,					initializer_range=self.initializer_range       ,					summary_type=self.summary_type       ,					use_proj=self.use_proj       ,					num_labels=self.num_labels       ,					bos_token_id=self.bos_token_id       ,					)






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Tuple											=				XLMModel(config=__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()
         lowerCAmelCase__     :int											=				model(__UpperCAmelCase       ,					lengths=__UpperCAmelCase       ,					langs=__UpperCAmelCase )
         lowerCAmelCase__     :Optional[int]											=				model(__UpperCAmelCase       ,					langs=__UpperCAmelCase )
         lowerCAmelCase__     :List[str]											=				model(__UpperCAmelCase )
         self.parent.assertEqual(result.last_hidden_state.shape       ,					(self.batch_size, self.seq_length, self.hidden_size) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :List[str]											=				XLMWithLMHeadModel(__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()

         lowerCAmelCase__     :Any											=				model(__UpperCAmelCase       ,					token_type_ids=__UpperCAmelCase       ,					labels=__UpperCAmelCase )
         self.parent.assertEqual(result.loss.shape       ,					() )
         self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.seq_length, self.vocab_size) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Tuple											=				XLMForQuestionAnsweringSimple(__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()

         lowerCAmelCase__     :str											=				model(__UpperCAmelCase )

         lowerCAmelCase__     :List[Any]											=				model(__UpperCAmelCase       ,					start_positions=__UpperCAmelCase       ,					end_positions=__UpperCAmelCase )
         lowerCAmelCase__     :Tuple											=				outputs
         self.parent.assertEqual(result.start_logits.shape       ,					(self.batch_size, self.seq_length) )
         self.parent.assertEqual(result.end_logits.shape       ,					(self.batch_size, self.seq_length) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[int]											=				XLMForQuestionAnswering(__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()

         lowerCAmelCase__     :Tuple											=				model(__UpperCAmelCase )

         lowerCAmelCase__     :str											=				model(
             __UpperCAmelCase       ,					start_positions=__UpperCAmelCase       ,					end_positions=__UpperCAmelCase       ,					cls_index=__UpperCAmelCase       ,					is_impossible=__UpperCAmelCase       ,					p_mask=__UpperCAmelCase       ,					)

         lowerCAmelCase__     :int											=				model(
             __UpperCAmelCase       ,					start_positions=__UpperCAmelCase       ,					end_positions=__UpperCAmelCase       ,					cls_index=__UpperCAmelCase       ,					is_impossible=__UpperCAmelCase       ,					)

         ((lowerCAmelCase__)				,							)     :Tuple											=				result_with_labels.to_tuple()

         lowerCAmelCase__     :Tuple											=				model(__UpperCAmelCase       ,					start_positions=__UpperCAmelCase       ,					end_positions=__UpperCAmelCase )

         ((lowerCAmelCase__)				,							)     :Any											=				result_with_labels.to_tuple()

         self.parent.assertEqual(result_with_labels.loss.shape       ,					() )
         self.parent.assertEqual(result.start_top_log_probs.shape       ,					(self.batch_size, model.config.start_n_top) )
         self.parent.assertEqual(result.start_top_index.shape       ,					(self.batch_size, model.config.start_n_top) )
         self.parent.assertEqual(
             result.end_top_log_probs.shape       ,					(self.batch_size, model.config.start_n_top * model.config.end_n_top) )
         self.parent.assertEqual(
             result.end_top_index.shape       ,					(self.batch_size, model.config.start_n_top * model.config.end_n_top) )
         self.parent.assertEqual(result.cls_logits.shape       ,					(self.batch_size,) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :int											=				XLMForSequenceClassification(__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()

         lowerCAmelCase__     :Optional[int]											=				model(__UpperCAmelCase )
         lowerCAmelCase__     :str											=				model(__UpperCAmelCase       ,					labels=__UpperCAmelCase )
         self.parent.assertEqual(result.loss.shape       ,					() )
         self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.type_sequence_label_size) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :Tuple											=				self.num_labels
         lowerCAmelCase__     :Any											=				XLMForTokenClassification(__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()

         lowerCAmelCase__     :Union[str, Any]											=				model(__UpperCAmelCase       ,					attention_mask=__UpperCAmelCase       ,					labels=__UpperCAmelCase )
         self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.seq_length, self.num_labels) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					):



         '''simple docstring'''

         lowerCAmelCase__     :List[str]											=				self.num_choices
         lowerCAmelCase__     :str											=				XLMForMultipleChoice(config=__UpperCAmelCase )
         model.to(__UpperCAmelCase )
         model.eval()
         lowerCAmelCase__     :str											=				input_ids.unsqueeze(1 ).expand(-1       ,					self.num_choices       ,					-1 ).contiguous()
         lowerCAmelCase__     :Tuple											=				token_type_ids.unsqueeze(1 ).expand(-1       ,					self.num_choices       ,					-1 ).contiguous()
         lowerCAmelCase__     :Dict											=				input_mask.unsqueeze(1 ).expand(-1       ,					self.num_choices       ,					-1 ).contiguous()
         lowerCAmelCase__     :Dict											=				model(
             __UpperCAmelCase       ,					attention_mask=__UpperCAmelCase       ,					token_type_ids=__UpperCAmelCase       ,					labels=__UpperCAmelCase       ,					)
         self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_choices) )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[int]											=				self.prepare_config_and_inputs()
         (
             (
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							(
             lowerCAmelCase__
         )				,							
         )     :Any											=				config_and_inputs
         lowerCAmelCase__     :Tuple											=				{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths}
         return config, inputs_dict






@require_torch
class    _lowerCAmelCase  (	a    ,  a    ,  a    ,  unittest.TestCase			):
       """simple docstring"""




       __magic_name__	:str						    =   (
           (
               XLMModel,
               XLMWithLMHeadModel,
               XLMForQuestionAnswering,
               XLMForSequenceClassification,
               XLMForQuestionAnsweringSimple,
               XLMForTokenClassification,
               XLMForMultipleChoice,
           )
           if is_torch_available()
           else ()
       )
       __magic_name__	:List[Any]						    =   (
           (XLMWithLMHeadModel,) if is_torch_available() else ()
       )  # TODO (PVP): Check other models whether language generation is also applicable
       __magic_name__	:Any						    =   (
           {
               """feature-extraction""": XLMModel,
               """fill-mask""": XLMWithLMHeadModel,
               """question-answering""": XLMForQuestionAnsweringSimple,
               """text-classification""": XLMForSequenceClassification,
               """text-generation""": XLMWithLMHeadModel,
               """token-classification""": XLMForTokenClassification,
               """zero-shot""": XLMForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         if (
             pipeline_test_casse_name == "QAPipelineTests"
             and tokenizer_name is not None
             and not tokenizer_name.endswith('Fast' )
         ):
           # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
           # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
           # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
           return True

         return False






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase=False ):



         '''simple docstring'''

         lowerCAmelCase__     :Dict											=				super()._prepare_for_class(__UpperCAmelCase       ,					__UpperCAmelCase       ,					return_labels=__UpperCAmelCase )

         if return_labels:
           if model_class.__name__ == "XLMForQuestionAnswering":
             lowerCAmelCase__     :Optional[int]											=				torch.zeros(
                 self.model_tester.batch_size       ,					dtype=torch.long       ,					device=__UpperCAmelCase )
             lowerCAmelCase__     :List[Any]											=				torch.zeros(
                 self.model_tester.batch_size       ,					dtype=torch.long       ,					device=__UpperCAmelCase )

         return inputs_dict






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :List[str]											=				XLMModelTester(self )
         lowerCAmelCase__     :Tuple											=				ConfigTester(self       ,					config_class=__UpperCAmelCase       ,					emb_dim=3_7 )






       def 	snake_case		(       self ):



         '''simple docstring'''

         self.config_tester.run_common_tests()






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :List[Any]											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_model(*__UpperCAmelCase )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[int]											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_lm_head(*__UpperCAmelCase )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Tuple											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_simple_qa(*__UpperCAmelCase )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :List[Any]											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_qa(*__UpperCAmelCase )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :List[str]											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_sequence_classif(*__UpperCAmelCase )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Any											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_token_classif(*__UpperCAmelCase )






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :str											=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_for_multiple_choice(*__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase=False       ,					__UpperCAmelCase=1 ):



         '''simple docstring'''

         self.assertIsInstance(__UpperCAmelCase       ,					__UpperCAmelCase )
         self.assertListEqual(
             [isinstance(__UpperCAmelCase       ,					__UpperCAmelCase ) for iter_attentions in attentions]       ,					[True] * len(__UpperCAmelCase ) )
         self.assertEqual(len(__UpperCAmelCase )       ,					(max_length - min_length) * num_beam_groups )

         for idx, iter_attentions in enumerate(__UpperCAmelCase ):
           # adds PAD dummy token
           lowerCAmelCase__     :Tuple											=				min_length + idx + 1
           lowerCAmelCase__     :int											=				min_length + idx + 1

           lowerCAmelCase__     :Dict											=				(
               batch_size * num_beam_groups,
               config.num_attention_heads,
               tgt_len,
               src_len,
           )
           # check attn size
           self.assertListEqual(
               [layer_attention.shape for layer_attention in iter_attentions]       ,					[expected_shape] * len(__UpperCAmelCase ) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase=False       ,					__UpperCAmelCase=1 ):



         '''simple docstring'''

         self.assertIsInstance(__UpperCAmelCase       ,					__UpperCAmelCase )
         self.assertListEqual(
             [isinstance(__UpperCAmelCase       ,					__UpperCAmelCase ) for iter_hidden_states in hidden_states]       ,					[True] * len(__UpperCAmelCase )       ,					)
         self.assertEqual(len(__UpperCAmelCase )       ,					(max_length - min_length) * num_beam_groups )

         for idx, iter_hidden_states in enumerate(__UpperCAmelCase ):
           # adds PAD dummy token
           lowerCAmelCase__     :Tuple											=				min_length + idx + 1
           lowerCAmelCase__     :Dict											=				(batch_size * num_beam_groups, seq_len, config.hidden_size)
           # check hidden size
           self.assertListEqual(
               [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]       ,					[expected_shape] * len(__UpperCAmelCase )       ,					)
         pass






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowerCAmelCase__     :List[str]											=				XLMModel.from_pretrained(__UpperCAmelCase )
           self.assertIsNotNone(__UpperCAmelCase )






@require_torch
class    _lowerCAmelCase  (	unittest.TestCase			):
       """simple docstring"""




       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Any											=				XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' )
         model.to(__UpperCAmelCase )
         lowerCAmelCase__     :Tuple											=				torch.tensor([[1_4, 4_4_7]]       ,					dtype=torch.long       ,					device=__UpperCAmelCase )  # the president
         lowerCAmelCase__     :Dict											=				[
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
         ]  # the president the president the president the president the president the president the president the president the president the president
         # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
         lowerCAmelCase__     :Tuple											=				model.generate(__UpperCAmelCase       ,					do_sample=__UpperCAmelCase )
         self.assertListEqual(output_ids[0].cpu().numpy().tolist()       ,					__UpperCAmelCase )







"""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


__A											=						["""gpt2"""]
__A											=						"""gpt2"""

if is_tf_available():






  class    _lowerCAmelCase  (	tf.Module			):
         """simple docstring"""




         def __init__(       self       ,					__UpperCAmelCase ):



           '''simple docstring'''

           super().__init__()
           lowerCAmelCase__     :List[str]											=				tokenizer
           lowerCAmelCase__     :Optional[int]											=				AutoConfig.from_pretrained(__UpperCAmelCase )
           lowerCAmelCase__     :Optional[Any]											=				TFGPTaLMHeadModel.from_config(__UpperCAmelCase )






         @tf.function(input_signature=(tf.TensorSpec((None,)       ,					tf.string       ,					name='text' ),) )
         def 	snake_case		(       self       ,					__UpperCAmelCase ):



           '''simple docstring'''

           lowerCAmelCase__     :str											=				self.tokenizer(__UpperCAmelCase )
           lowerCAmelCase__     :int											=				tokenized['input_ids'].to_tensor()

           lowerCAmelCase__     :Optional[Any]											=				tf.cast(input_ids_dense > 0       ,					tf.intaa )
           # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

           lowerCAmelCase__     :int											=				self.model(input_ids=__UpperCAmelCase       ,					attention_mask=__UpperCAmelCase )['logits']

           return outputs






@require_tf
@require_keras_nlp
class    _lowerCAmelCase  (	unittest.TestCase			):
       """simple docstring"""




       def 	snake_case		(       self ):



         '''simple docstring'''

         super().setUp()

         lowerCAmelCase__     :List[str]											=				[GPTaTokenizer.from_pretrained(__UpperCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
         lowerCAmelCase__     :Union[str, Any]											=				[TFGPTaTokenizer.from_pretrained(__UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS]
         assert len(self.tokenizers ) == len(self.tf_tokenizers )

         lowerCAmelCase__     :int											=				[
             '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ċ, ꝼ',
         ]
         lowerCAmelCase__     :str											=				list(zip(self.test_sentences       ,					self.test_sentences[::-1] ) )






       def 	snake_case		(       self ):



         '''simple docstring'''

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

             for key in python_outputs.keys():
               # convert them to numpy to avoid messing with ragged tensors
               lowerCAmelCase__     :Optional[int]											=				python_outputs[key].numpy()
               lowerCAmelCase__     :List[str]											=				tf_outputs[key].numpy()

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






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           lowerCAmelCase__     :Optional[int]											=				tf.function(__UpperCAmelCase )
           for test_inputs in self.test_sentences:
             lowerCAmelCase__     :Any											=				tf.constant(__UpperCAmelCase )
             lowerCAmelCase__     :int											=				compiled_tokenizer(__UpperCAmelCase )
             lowerCAmelCase__     :Any											=				tf_tokenizer(__UpperCAmelCase )

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






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           lowerCAmelCase__     :List[str]											=				ModelToSave(tokenizer=__UpperCAmelCase )
           lowerCAmelCase__     :Union[str, Any]											=				tf.convert_to_tensor([self.test_sentences[0]] )
           lowerCAmelCase__     :List[str]											=				model.serving(__UpperCAmelCase )  # Build model with some sample inputs
           with TemporaryDirectory() as tempdir:
             lowerCAmelCase__     :Union[str, Any]											=				Path(__UpperCAmelCase ) / 'saved.model'
             tf.saved_model.save(__UpperCAmelCase       ,					__UpperCAmelCase       ,					signatures={'serving_default': model.serving} )
             lowerCAmelCase__     :str											=				tf.saved_model.load(__UpperCAmelCase )
           lowerCAmelCase__     :Dict											=				loaded_model.signatures['serving_default'](__UpperCAmelCase )['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 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           lowerCAmelCase__     :List[str]											=				tf.convert_to_tensor([self.test_sentences[0]] )
           lowerCAmelCase__     :List[str]											=				tf_tokenizer(__UpperCAmelCase )  # Build model with some sample inputs

           lowerCAmelCase__     :Union[str, Any]											=				tf_tokenizer.get_config()
           lowerCAmelCase__     :Tuple											=				TFGPTaTokenizer.from_config(__UpperCAmelCase )
           lowerCAmelCase__     :Tuple											=				model_from_config(__UpperCAmelCase )

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






       @slow
       def 	snake_case		(       self ):



         '''simple docstring'''

         for tf_tokenizer in self.tf_tokenizers:
           # for the test to run
           lowerCAmelCase__     :int											=				1_2_3_1_2_3

           for max_length in [3, 5, 1_0_2_4]:
             lowerCAmelCase__     :Tuple											=				tf.convert_to_tensor([self.test_sentences[0]] )
             lowerCAmelCase__     :List[str]											=				tf_tokenizer(__UpperCAmelCase       ,					max_length=__UpperCAmelCase )

             lowerCAmelCase__     :Union[str, Any]											=				out['input_ids'].numpy().shape[1]

             assert out_length == max_length
