
from __future__ import annotations

import unittest

from transformers import MPNetConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
   import tensorflow as tf

   from transformers.models.mpnet.modeling_tf_mpnet import (
       TFMPNetForMaskedLM,
       TFMPNetForMultipleChoice,
       TFMPNetForQuestionAnswering,
       TFMPNetForSequenceClassification,
       TFMPNetForTokenClassification,
       TFMPNetModel,
   )






class UpperCAmelCase     :





   '''simple docstring'''


   def __init__(      self  :							List[Any]    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							List[str]=1_3    ,    lowerCAmelCase_  :							List[Any]=7    ,    lowerCAmelCase_  :							Any=True    ,    lowerCAmelCase_  :							Optional[Any]=True    ,    lowerCAmelCase_  :							Optional[int]=False    ,    lowerCAmelCase_  :							List[Any]=True    ,    lowerCAmelCase_  :							List[str]=9_9    ,    lowerCAmelCase_  :							List[Any]=6_4    ,    lowerCAmelCase_  :							str=2    ,    lowerCAmelCase_  :							Union[str, Any]=4    ,    lowerCAmelCase_  :							Union[str, Any]=6_4    ,    lowerCAmelCase_  :							int="gelu"    ,    lowerCAmelCase_  :							Any=0.1    ,    lowerCAmelCase_  :							int=0.1    ,    lowerCAmelCase_  :							str=5_1_2    ,    lowerCAmelCase_  :							str=1_6    ,    lowerCAmelCase_  :							str=2    ,    lowerCAmelCase_  :							str=0.02    ,    lowerCAmelCase_  :							List[str]=3    ,    lowerCAmelCase_  :							str=4    ,    lowerCAmelCase_  :							Any=None    ,    ):

      """simple docstring"""
      _A:						int	    = parent
      _A:						Optional[int]	    = batch_size
      _A:						str	    = seq_length
      _A:						List[str]	    = is_training
      _A:						List[Any]	    = use_input_mask
      _A:						Dict	    = use_token_type_ids
      _A:						Dict	    = use_labels
      _A:						Any	    = vocab_size
      _A:						Tuple	    = hidden_size
      _A:						Dict	    = num_hidden_layers
      _A:						str	    = num_attention_heads
      _A:						Tuple	    = intermediate_size
      _A:						Any	    = hidden_act
      _A:						Dict	    = hidden_dropout_prob
      _A:						Tuple	    = attention_probs_dropout_prob
      _A:						Dict	    = max_position_embeddings
      _A:						Any	    = type_vocab_size
      _A:						List[Any]	    = type_sequence_label_size
      _A:						Tuple	    = initializer_range
      _A:						List[str]	    = num_labels
      _A:						Optional[Any]	    = num_choices
      _A:						int	    = scope


   def 				__magic_name__       (      self  :							Dict  ):

      """simple docstring"""
      _A:						List[str]	    = ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size  )

      _A:						int	    = None
      if self.use_input_mask:
         _A:						Dict	    = random_attention_mask([self.batch_size, self.seq_length]  )

      _A:						Union[str, Any]	    = None
      _A:						str	    = None
      _A:						Optional[int]	    = None
      if self.use_labels:
         _A:						List[str]	    = ids_tensor([self.batch_size]    ,    self.type_sequence_label_size  )
         _A:						int	    = ids_tensor([self.batch_size, self.seq_length]    ,    self.num_labels  )
         _A:						Dict	    = ids_tensor([self.batch_size]    ,    self.num_choices  )

      _A:						List[str]	    = MPNetConfig(
          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    ,    initializer_range=self.initializer_range    ,    )
      return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels


   def 				__magic_name__       (      self  :							Optional[int]    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Any    ,    lowerCAmelCase_  :							Tuple    ,    lowerCAmelCase_  :							str    ,    lowerCAmelCase_  :							Dict  ):

      """simple docstring"""
      _A:						List[Any]	    = TFMPNetModel(config=lowerCAmelCase_  )
      _A:						Dict	    = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
      _A:						Optional[Any]	    = model(lowerCAmelCase_  )
      _A:						int	    = [input_ids, input_mask]
      _A:						Tuple	    = model(lowerCAmelCase_  )
      self.parent.assertEqual(result.last_hidden_state.shape    ,    (self.batch_size, self.seq_length, self.hidden_size)  )


   def 				__magic_name__       (      self  :							Optional[Any]    ,    lowerCAmelCase_  :							Union[str, Any]    ,    lowerCAmelCase_  :							str    ,    lowerCAmelCase_  :							Union[str, Any]    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Any    ,    lowerCAmelCase_  :							Union[str, Any]  ):

      """simple docstring"""
      _A:						Dict	    = TFMPNetForMaskedLM(config=lowerCAmelCase_  )
      _A:						Optional[int]	    = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
      _A:						int	    = model(lowerCAmelCase_  )
      self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.seq_length, self.vocab_size)  )


   def 				__magic_name__       (      self  :							Any    ,    lowerCAmelCase_  :							int    ,    lowerCAmelCase_  :							int    ,    lowerCAmelCase_  :							Tuple    ,    lowerCAmelCase_  :							str    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Optional[int]  ):

      """simple docstring"""
      _A:						Tuple	    = TFMPNetForQuestionAnswering(config=lowerCAmelCase_  )
      _A:						List[str]	    = {
          '''input_ids''': input_ids,
          '''attention_mask''': input_mask,
      }
      _A:						Dict	    = model(lowerCAmelCase_  )
      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 				__magic_name__       (      self  :							List[Any]    ,    lowerCAmelCase_  :							Dict    ,    lowerCAmelCase_  :							List[str]    ,    lowerCAmelCase_  :							List[str]    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Optional[Any]  ):

      """simple docstring"""
      _A:						List[str]	    = self.num_labels
      _A:						Dict	    = TFMPNetForSequenceClassification(lowerCAmelCase_  )
      _A:						Union[str, Any]	    = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
      _A:						List[str]	    = model(lowerCAmelCase_  )
      self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.num_labels)  )


   def 				__magic_name__       (      self  :							int    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							List[str]    ,    lowerCAmelCase_  :							int    ,    lowerCAmelCase_  :							Any    ,    lowerCAmelCase_  :							Dict    ,    lowerCAmelCase_  :							List[str]  ):

      """simple docstring"""
      _A:						Tuple	    = self.num_choices
      _A:						Optional[int]	    = TFMPNetForMultipleChoice(lowerCAmelCase_  )
      _A:						int	    = tf.tile(tf.expand_dims(lowerCAmelCase_    ,    1  )    ,    (1, self.num_choices, 1)  )
      _A:						Dict	    = tf.tile(tf.expand_dims(lowerCAmelCase_    ,    1  )    ,    (1, self.num_choices, 1)  )
      _A:						Any	    = {
          '''input_ids''': multiple_choice_inputs_ids,
          '''attention_mask''': multiple_choice_input_mask,
      }
      _A:						Optional[int]	    = model(lowerCAmelCase_  )
      self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.num_choices)  )


   def 				__magic_name__       (      self  :							str    ,    lowerCAmelCase_  :							Any    ,    lowerCAmelCase_  :							Tuple    ,    lowerCAmelCase_  :							Any    ,    lowerCAmelCase_  :							Optional[Any]    ,    lowerCAmelCase_  :							Optional[int]    ,    lowerCAmelCase_  :							Optional[int]  ):

      """simple docstring"""
      _A:						str	    = self.num_labels
      _A:						Optional[int]	    = TFMPNetForTokenClassification(lowerCAmelCase_  )
      _A:						Any	    = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
      _A:						Optional[int]	    = model(lowerCAmelCase_  )
      self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.seq_length, self.num_labels)  )


   def 				__magic_name__       (      self  :							Any  ):

      """simple docstring"""
      _A:						Union[str, Any]	    = self.prepare_config_and_inputs()
      ((_A)    ,						(_A)    ,						(_A)    ,						(_A)    ,						(_A)    ,						(_A)):						Tuple	    = config_and_inputs
      _A:						str	    = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
      return config, inputs_dict






@require_tf
class UpperCAmelCase     (		SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							unittest.TestCase     ):





   '''simple docstring'''
   __UpperCamelCase	:					str				       =					(
       (
           TFMPNetForMaskedLM,
           TFMPNetForMultipleChoice,
           TFMPNetForQuestionAnswering,
           TFMPNetForSequenceClassification,
           TFMPNetForTokenClassification,
           TFMPNetModel,
       )
       if is_tf_available()
       else ()
   )
   __UpperCamelCase	:					int				       =					(
       {
           '''feature-extraction''': TFMPNetModel,
           '''fill-mask''': TFMPNetForMaskedLM,
           '''question-answering''': TFMPNetForQuestionAnswering,
           '''text-classification''': TFMPNetForSequenceClassification,
           '''token-classification''': TFMPNetForTokenClassification,
           '''zero-shot''': TFMPNetForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   __UpperCamelCase	:					str				       =					False
   __UpperCamelCase	:					Optional[Any]				       =					False


   def 				__magic_name__       (      self  :							Optional[int]  ):

      """simple docstring"""
      _A:						Optional[int]	    = TFMPNetModelTester(self  )
      _A:						List[str]	    = ConfigTester(self    ,    config_class=lowerCAmelCase_    ,    hidden_size=3_7  )


   def 				__magic_name__       (      self  :							Optional[Any]  ):

      """simple docstring"""
      self.config_tester.run_common_tests()


   def 				__magic_name__       (      self  :							List[str]  ):

      """simple docstring"""
      _A:						Tuple	    = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_model(*lowerCAmelCase_  )


   def 				__magic_name__       (      self  :							Optional[int]  ):

      """simple docstring"""
      _A:						Union[str, Any]	    = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_masked_lm(*lowerCAmelCase_  )


   def 				__magic_name__       (      self  :							List[str]  ):

      """simple docstring"""
      _A:						int	    = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_question_answering(*lowerCAmelCase_  )


   def 				__magic_name__       (      self  :							List[str]  ):

      """simple docstring"""
      _A:						Tuple	    = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowerCAmelCase_  )


   def 				__magic_name__       (      self  :							Union[str, Any]  ):

      """simple docstring"""
      _A:						Dict	    = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowerCAmelCase_  )


   def 				__magic_name__       (      self  :							List[Any]  ):

      """simple docstring"""
      _A:						int	    = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_token_classification(*lowerCAmelCase_  )


   @slow
   def 				__magic_name__       (      self  :							Optional[int]  ):

      """simple docstring"""
      for model_name in ["microsoft/mpnet-base"]:
         _A:						Any	    = TFMPNetModel.from_pretrained(lowerCAmelCase_  )
         self.assertIsNotNone(lowerCAmelCase_  )






@require_tf
class UpperCAmelCase     (		unittest.TestCase     ):





   '''simple docstring'''


   @slow
   def 				__magic_name__       (      self  :							Optional[Any]  ):

      """simple docstring"""
      _A:						Dict	    = TFMPNetModel.from_pretrained('''microsoft/mpnet-base'''  )
      _A:						Union[str, Any]	    = tf.constant([[0, 1, 2, 3, 4, 5]]  )
      _A:						Tuple	    = model(lowerCAmelCase_  )[0]

      _A:						Dict	    = [1, 6, 7_6_8]
      self.assertEqual(output.shape    ,    lowerCAmelCase_  )

      _A:						Dict	    = tf.constant(
          [
              [
                  [-0.1067172, 0.08216473, 0.0024543],
                  [-0.03465879, 0.8354118, -0.03252288],
                  [-0.06569476, -0.12424111, -0.0494436],
              ]
          ]  )
      tf.debugging.assert_near(output[:, :3, :3]    ,    lowerCAmelCase_    ,    atol=1e-4  )





# This test is meant to be run in on an instance with TPUs like this:
#
#   python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py
#
# Replace 8 with the number of TPU cores you have.
#

import sys
from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.utils import logging


UpperCAmelCase__	:  Union[str, Any]      =   logging.get_logger(__name__)


if is_torch_available():
   import torch
   from torch import nn
   from torch.utils.data import Dataset

   from transformers import Trainer






   class UpperCAmelCase     (		SCREAMING_SNAKE_CASE__     ):





      '''simple docstring'''


      def __init__(      self  :							List[Any]    ,    lowerCAmelCase_  :							int = 1_0_1  ):

         """simple docstring"""
         _A:						str	    = length


      def __len__(      self  :							List[Any]  ):

         """simple docstring"""
         return self.length


      def __getitem__(      self  :							Any    ,    lowerCAmelCase_  :							Any  ):

         """simple docstring"""
         return i






   class UpperCAmelCase     :





      '''simple docstring'''


      def __call__(      self  :							Any    ,    lowerCAmelCase_  :							Union[str, Any]  ):

         """simple docstring"""
         return {"input_ids": torch.tensor(lowerCAmelCase_  ), "labels": torch.tensor(lowerCAmelCase_  )}






   class UpperCAmelCase     (		nn.Module     ):





      '''simple docstring'''


      def __init__(      self  :							str  ):

         """simple docstring"""
         super().__init__()
         # Add some (unused) params otherwise DDP will complain.
         _A:						Tuple	    = nn.Linear(1_2_0    ,    8_0  )


      def 				__magic_name__       (      self  :							List[Any]    ,    lowerCAmelCase_  :							List[str]    ,    lowerCAmelCase_  :							List[str]=None  ):

         """simple docstring"""
         if labels is not None:
            return torch.tensor(0.0    ,    device=input_ids.device  ), input_ids
         else:
            return input_ids






def 						lowerCamelCase__							(      )   ->     Optional[int]:
   _A:						Any	    = HfArgumentParser((TrainingArguments,)   )
   sys.argv += ["--output_dir", "./examples"]
   _A:						Any	    = parser.parse_args_into_dataclasses()[0]

   logger.warning(
       f"""Process rank: {training_args.local_rank}, device: {training_args.device}, """
       f"""tpu_num_cores: {training_args.tpu_num_cores}"""	,	)

   # Essentially, what we want to verify in the distributed case is
   # that we get all samples back, in the right order.
   # (this is crucial for prediction for instance)
   for dataset_length in [10_01, 2_56, 15]:
      _A:						Any	    = DummyDataset(a   )

      def compute_metrics(a   ) -> Dict:
         _A:						Dict	    = list(range(len(a   )   )   )
         _A:						List[str]	    = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
         return {"success": success}

      _A:						Optional[Any]	    = Trainer(
          model=DummyModel()	,	args=a	,	data_collator=DummyDataCollator()	,	eval_dataset=a	,	compute_metrics=a	,	)
      _A:						List[str]	    = trainer.evaluate()
      logger.info(a   )
      if metrics["eval_success"] is not True:
         logger.error(a   )
         exit(1   )

      _A:						Optional[Any]	    = trainer.predict(a   )
      logger.info(p.metrics   )
      if p.metrics["test_success"] is not True:
         logger.error(p.metrics   )
         exit(1   )

      _A:						str	    = 2

      _A:						Optional[Any]	    = trainer.evaluate()
      logger.info(a   )
      if metrics["eval_success"] is not True:
         logger.error(a   )
         exit(1   )

      _A:						Optional[Any]	    = trainer.predict(a   )
      logger.info(p.metrics   )
      if p.metrics["test_success"] is not True:
         logger.error(p.metrics   )
         exit(1   )

      _A:						str	    = None

   logger.info('''🔥 All distributed tests successful'''   )






def 						lowerCamelCase__							(      a   )   ->     Optional[Any]:
   # For xla_spawn (TPUs)
   main()


if __name__ == "__main__":
   main()



