





import unittest

from transformers import DebertaVaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import (
        DebertaVaForMaskedLM,
        DebertaVaForMultipleChoice,
        DebertaVaForQuestionAnswering,
        DebertaVaForSequenceClassification,
        DebertaVaForTokenClassification,
        DebertaVaModel,
    )
    from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=7					,  lowercase=True					,  lowercase=True					,  lowercase=True					,  lowercase=True					,  lowercase=99					,  lowercase=32					,  lowercase=5					,  lowercase=4					,  lowercase=37					,  lowercase="gelu"					,  lowercase=0.1					,  lowercase=0.1					,  lowercase=512					,  lowercase=16					,  lowercase=2					,  lowercase=0.02					,  lowercase=False					,  lowercase=True					,  lowercase="None"					,  lowercase=3					,  lowercase=4					,  lowercase=None					,  )			->						int:







          '''simple docstring'''

          a__						:	Optional[int] =				parent
          a__						:	List[str] =				batch_size
          a__						:	Optional[Any] =				seq_length
          a__						:	Any =				is_training
          a__						:	Tuple =				use_input_mask
          a__						:	List[Any] =				use_token_type_ids
          a__						:	Optional[Any] =				use_labels
          a__						:	int =				vocab_size
          a__						:	List[Any] =				hidden_size
          a__						:	Optional[int] =				num_hidden_layers
          a__						:	Any =				num_attention_heads
          a__						:	List[Any] =				intermediate_size
          a__						:	Any =				hidden_act
          a__						:	Optional[int] =				hidden_dropout_prob
          a__						:	int =				attention_probs_dropout_prob
          a__						:	Tuple =				max_position_embeddings
          a__						:	Optional[Any] =				type_vocab_size
          a__						:	Optional[Any] =				type_sequence_label_size
          a__						:	Union[str, Any] =				initializer_range
          a__						:	List[str] =				num_labels
          a__						:	Union[str, Any] =				num_choices
          a__						:	Optional[Any] =				relative_attention
          a__						:	List[str] =				position_biased_input
          a__						:	List[str] =				pos_att_type
          a__						:	Optional[Any] =				scope

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	Union[str, Any] =				ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size)

          a__						:	Union[str, Any] =				None
          if self.use_input_mask:
                 a__						:	Union[str, Any] =				ids_tensor([self.batch_size, self.seq_length]					,  vocab_size=2)

          a__						:	Dict =				None
          if self.use_token_type_ids:
                 a__						:	List[Any] =				ids_tensor([self.batch_size, self.seq_length]					,  self.type_vocab_size)

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

          a__						:	Dict =				self.get_config()

          return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          return DebertaVaConfig(
              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					,  initializer_range=self.initializer_range					,  relative_attention=self.relative_attention					,  position_biased_input=self.position_biased_input					,  pos_att_type=self.pos_att_type					,  )

   def 							__lowercase		(					self					,  lowercase)			->						Optional[Any]:







          '''simple docstring'''

          self.parent.assertListEqual(list(result.loss.size())					,  [])

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	List[str] =				DebertaVaModel(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	List[Any] =				model(lowercase					,  attention_mask=lowercase					,  token_type_ids=lowercase)[0]
          a__						:	str =				model(lowercase					,  token_type_ids=lowercase)[0]
          a__						:	Tuple =				model(lowercase)[0]

          self.parent.assertListEqual(list(sequence_output.size())					,  [self.batch_size, self.seq_length, self.hidden_size])

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						Tuple:







          '''simple docstring'''

          a__						:	Dict =				DebertaVaForMaskedLM(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	str =				model(lowercase					,  attention_mask=lowercase					,  token_type_ids=lowercase					,  labels=lowercase)

          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.vocab_size))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						Dict:







          '''simple docstring'''

          a__						:	Any =				self.num_labels
          a__						:	List[str] =				DebertaVaForSequenceClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Optional[int] =				model(lowercase					,  attention_mask=lowercase					,  token_type_ids=lowercase					,  labels=lowercase)
          self.parent.assertListEqual(list(result.logits.size())					,  [self.batch_size, self.num_labels])
          self.check_loss_output(lowercase)

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						List[Any]:







          '''simple docstring'''

          a__						:	Optional[Any] =				self.num_labels
          a__						:	Dict =				DebertaVaForTokenClassification(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	str =				model(lowercase					,  attention_mask=lowercase					,  token_type_ids=lowercase					,  labels=lowercase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.num_labels))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						Tuple:







          '''simple docstring'''

          a__						:	Dict =				DebertaVaForQuestionAnswering(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Any =				model(
              lowercase					,  attention_mask=lowercase					,  token_type_ids=lowercase					,  start_positions=lowercase					,  end_positions=lowercase					,  )
          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 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						Optional[int]:







          '''simple docstring'''

          a__						:	Dict =				DebertaVaForMultipleChoice(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Any =				input_ids.unsqueeze(1).expand(-1					,  self.num_choices					,  -1).contiguous()
          a__						:	int =				token_type_ids.unsqueeze(1).expand(-1					,  self.num_choices					,  -1).contiguous()
          a__						:	int =				input_mask.unsqueeze(1).expand(-1					,  self.num_choices					,  -1).contiguous()
          a__						:	Optional[int] =				model(
              lowercase					,  attention_mask=lowercase					,  token_type_ids=lowercase					,  labels=lowercase					,  )
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_choices))

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__						:	Union[str, Any] =				self.prepare_config_and_inputs()
          (
              (
              a__
          ) ,							(
              a__
          ) ,							(
              a__
          ) ,							(
              a__
          ) ,							(
              a__
          ) ,							(
              a__
          ) ,							(
              a__
          ) ,							
          )						:	Optional[int] =				config_and_inputs
          a__						:	Union[str, Any] =				{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
          return config, inputs_dict





@require_torch
class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				Dict         =  (
       (
           DebertaVaModel,
           DebertaVaForMaskedLM,
           DebertaVaForSequenceClassification,
           DebertaVaForTokenClassification,
           DebertaVaForQuestionAnswering,
           DebertaVaForMultipleChoice,
       )
       if is_torch_available()
       else ()
   )
   __A   :				Tuple         =  (
       {
           '''feature-extraction''': DebertaVaModel,
           '''fill-mask''': DebertaVaForMaskedLM,
           '''question-answering''': DebertaVaForQuestionAnswering,
           '''text-classification''': DebertaVaForSequenceClassification,
           '''token-classification''': DebertaVaForTokenClassification,
           '''zero-shot''': DebertaVaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )

   __A   :				Union[str, Any]         =  True
   __A   :				Any         =  False
   __A   :				List[str]         =  False
   __A   :				str         =  False
   __A   :				Any         =  False

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	int =				DebertaVaModelTester(self)
          a__						:	Dict =				ConfigTester(self					,  config_class=lowercase					,  hidden_size=37)

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__						:	str =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_model(*lowercase)

   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Optional[Any] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_sequence_classification(*lowercase)

   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	List[Any] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_masked_lm(*lowercase)

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	str =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_question_answering(*lowercase)

   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          a__						:	List[Any] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_token_classification(*lowercase)

   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          a__						:	int =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_multiple_choice(*lowercase)

   @slow
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	List[Any] =				DebertaVaModel.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)





@require_torch
@require_sentencepiece
@require_tokenizers
class  A__    (							unittest.TestCase	):




   """simple docstring"""



   @unittest.skip(reason='Model not available yet')
   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          pass

   @slow
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          a__						:	Any =				DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge')

          a__						:	int =				torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]])
          a__						:	Optional[int] =				torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
          with torch.no_grad():
                 a__						:	Optional[Any] =				model(lowercase					,  attention_mask=lowercase)[0]
          # compare the actual values for a slice.
          a__						:	int =				torch.tensor(
              [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]])
          self.assertTrue(torch.allclose(output[:, 1:4, 1:4]					,  lowercase					,  atol=1e-4)					,  F'{output[:, 1:4, 1:4]}')



from __future__ import annotations

import unittest

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


if is_tf_available():
					import tensorflow as tf

					from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM





@require_tf
@require_sentencepiece
@require_tokenizers
class 					lowercase__						(   unittest.TestCase):


						@slow
						def        __A       (       self	:				Union[str, Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Any							=							TFAutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small'''						)
												SCREAMING_SNAKE_CASE							:    List[str]							=							AutoTokenizer.from_pretrained('''google/mt5-small'''						)

												SCREAMING_SNAKE_CASE							:    Optional[int]							=							tokenizer('''Hello there'''    ,		return_tensors='''tf'''						).input_ids
												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							tokenizer('''Hi I am'''    ,		return_tensors='''tf'''						).input_ids

												SCREAMING_SNAKE_CASE							:    List[Any]							=							model(UpperCamelCase__    ,		labels=UpperCamelCase__						).loss
												SCREAMING_SNAKE_CASE							:    int							=							-tf.math.reduce_mean(UpperCamelCase__						).numpy()

												SCREAMING_SNAKE_CASE							:    List[str]							=							-21.22_8168
												self.assertTrue(abs(mtf_score - EXPECTED_SCORE						) < 2E-4						)





