



from __future__ import annotations

import unittest

from transformers import DebertaVaConfig, 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 import (
           TFDebertaVaForMaskedLM,
           TFDebertaVaForQuestionAnswering,
           TFDebertaVaForSequenceClassification,
           TFDebertaVaForTokenClassification,
           TFDebertaVaModel,
       )



class    UpperCAmelCase__:

   '''simple docstring'''




   def __init__(    self	:      int      ,					lowerCAmelCase	:      List[str]      ,					lowerCAmelCase	:      Optional[int]=13      ,					lowerCAmelCase	:      Optional[Any]=7      ,					lowerCAmelCase	:      List[str]=True      ,					lowerCAmelCase	:      Union[str, Any]=True      ,					lowerCAmelCase	:      Any=True      ,					lowerCAmelCase	:      Optional[int]=True      ,					lowerCAmelCase	:      Optional[int]=99      ,					lowerCAmelCase	:      int=32      ,					lowerCAmelCase	:      List[str]=2      ,					lowerCAmelCase	:      int=4      ,					lowerCAmelCase	:      Optional[Any]=37      ,					lowerCAmelCase	:      Tuple="gelu"      ,					lowerCAmelCase	:      int=0.1      ,					lowerCAmelCase	:      Optional[Any]=0.1      ,					lowerCAmelCase	:      Optional[Any]=5_12      ,					lowerCAmelCase	:      int=16      ,					lowerCAmelCase	:      Any=2      ,					lowerCAmelCase	:      Tuple=0.02      ,					lowerCAmelCase	:      Optional[Any]=False      ,					lowerCAmelCase	:      List[Any]=True      ,					lowerCAmelCase	:      Tuple="None"      ,					lowerCAmelCase	:      Optional[Any]=3      ,					lowerCAmelCase	:      Dict=4      ,					lowerCAmelCase	:      Tuple=None      ,					)						->					int:




         """simple docstring"""

         lowercase__  =	parent
         lowercase__  =	batch_size
         lowercase__  =	seq_length
         lowercase__  =	is_training
         lowercase__  =	use_input_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_labels
         lowercase__  =	num_choices
         lowercase__  =	relative_attention
         lowercase__  =	position_biased_input
         lowercase__  =	pos_att_type
         lowercase__  =	scope


   def       UpperCAmelCase		(    self	:      Tuple)						->					List[Any]:




         """simple docstring"""

         lowercase__  =	ids_tensor([self.batch_size, self.seq_length]      ,					self.vocab_size)

         lowercase__  =	None
         if self.use_input_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__  =	None
         lowercase__  =	None
         lowercase__  =	None
         if self.use_labels:
               lowercase__  =	ids_tensor([self.batch_size]      ,					self.type_sequence_label_size)
               lowercase__  =	ids_tensor([self.batch_size, self.seq_length]      ,					self.num_labels)

         lowercase__  =	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      ,					relative_attention=self.relative_attention      ,					position_biased_input=self.position_biased_input      ,					initializer_range=self.initializer_range      ,					return_dict=lowerCAmelCase      ,					)

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


   def       UpperCAmelCase		(    self	:      Optional[Any]      ,					lowerCAmelCase	:      Any      ,					lowerCAmelCase	:      Union[str, Any]      ,					lowerCAmelCase	:      Dict      ,					lowerCAmelCase	:      List[str]      ,					lowerCAmelCase	:      Any      ,					lowerCAmelCase	:      str      ,					lowerCAmelCase	:      Optional[int])						->					int:




         """simple docstring"""

         lowercase__  =	TFDebertaVaModel(config=lowerCAmelCase)
         lowercase__  =	{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}

         lowercase__  =	[input_ids, input_mask]
         lowercase__  =	model(lowerCAmelCase)

         lowercase__  =	model(lowerCAmelCase)

         self.parent.assertEqual(result.last_hidden_state.shape      ,					(self.batch_size, self.seq_length, self.hidden_size))


   def       UpperCAmelCase		(    self	:      List[str]      ,					lowerCAmelCase	:      List[str]      ,					lowerCAmelCase	:      Tuple      ,					lowerCAmelCase	:      Dict      ,					lowerCAmelCase	:      Tuple      ,					lowerCAmelCase	:      Tuple      ,					lowerCAmelCase	:      Dict      ,					lowerCAmelCase	:      List[Any])						->					Optional[int]:




         """simple docstring"""

         lowercase__  =	TFDebertaVaForMaskedLM(config=lowerCAmelCase)
         lowercase__  =	{
             'input_ids': input_ids,
             'attention_mask': input_mask,
             'token_type_ids': token_type_ids,
         }
         lowercase__  =	model(lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.seq_length, self.vocab_size))


   def       UpperCAmelCase		(    self	:      Optional[Any]      ,					lowerCAmelCase	:      int      ,					lowerCAmelCase	:      int      ,					lowerCAmelCase	:      Tuple      ,					lowerCAmelCase	:      Union[str, Any]      ,					lowerCAmelCase	:      Optional[Any]      ,					lowerCAmelCase	:      str      ,					lowerCAmelCase	:      List[str])						->					List[str]:




         """simple docstring"""

         lowercase__  =	self.num_labels
         lowercase__  =	TFDebertaVaForSequenceClassification(config=lowerCAmelCase)
         lowercase__  =	{
             'input_ids': input_ids,
             'attention_mask': input_mask,
             'token_type_ids': token_type_ids,
         }

         lowercase__  =	model(lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.num_labels))


   def       UpperCAmelCase		(    self	:      int      ,					lowerCAmelCase	:      List[str]      ,					lowerCAmelCase	:      Any      ,					lowerCAmelCase	:      List[Any]      ,					lowerCAmelCase	:      Dict      ,					lowerCAmelCase	:      int      ,					lowerCAmelCase	:      Union[str, Any]      ,					lowerCAmelCase	:      List[str])						->					int:




         """simple docstring"""

         lowercase__  =	self.num_labels
         lowercase__  =	TFDebertaVaForTokenClassification(config=lowerCAmelCase)
         lowercase__  =	{
             'input_ids': input_ids,
             'attention_mask': input_mask,
             'token_type_ids': token_type_ids,
         }
         lowercase__  =	model(lowerCAmelCase)
         self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.seq_length, self.num_labels))


   def       UpperCAmelCase		(    self	:      Any      ,					lowerCAmelCase	:      str      ,					lowerCAmelCase	:      Union[str, Any]      ,					lowerCAmelCase	:      List[str]      ,					lowerCAmelCase	:      int      ,					lowerCAmelCase	:      Optional[Any]      ,					lowerCAmelCase	:      Optional[Any]      ,					lowerCAmelCase	:      List[Any])						->					Tuple:




         """simple docstring"""

         lowercase__  =	TFDebertaVaForQuestionAnswering(config=lowerCAmelCase)
         lowercase__  =	{
             'input_ids': input_ids,
             'attention_mask': input_mask,
             'token_type_ids': token_type_ids,
         }

         lowercase__  =	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       UpperCAmelCase		(    self	:      int)						->					Optional[int]:




         """simple docstring"""

         lowercase__  =	self.prepare_config_and_inputs()
         (
             (
             lowercase__
         ),						(
             lowercase__
         ),						(
             lowercase__
         ),						(
             lowercase__
         ),						(
             lowercase__
         ),						(
             lowercase__
         ),						(
             lowercase__
         ),						
         )  =	config_and_inputs
         lowercase__  =	{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
         return config, inputs_dict



@require_tf
class    UpperCAmelCase__(				lowerCamelCase  ,				lowerCamelCase  ,				unittest.TestCase						):

   '''simple docstring'''




   A     :	str												=     (
       (
           TFDebertaVaModel,
           TFDebertaVaForMaskedLM,
           TFDebertaVaForQuestionAnswering,
           TFDebertaVaForSequenceClassification,
           TFDebertaVaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   A     :	str												=     (
       {
           "feature-extraction": TFDebertaVaModel,
           "fill-mask": TFDebertaVaForMaskedLM,
           "question-answering": TFDebertaVaForQuestionAnswering,
           "text-classification": TFDebertaVaForSequenceClassification,
           "token-classification": TFDebertaVaForTokenClassification,
           "zero-shot": TFDebertaVaForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )

   A     :	int												=     False
   A     :	Dict												=     False


   def       UpperCAmelCase		(    self	:      Optional[Any])						->					List[str]:




         """simple docstring"""

         lowercase__  =	TFDebertaVaModelTester(self)
         lowercase__  =	ConfigTester(self      ,					config_class=lowerCAmelCase      ,					hidden_size=37)


   def       UpperCAmelCase		(    self	:      List[str])						->					int:




         """simple docstring"""

         self.config_tester.run_common_tests()


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




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      int)						->					Any:




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      Optional[int])						->					Optional[Any]:




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      Any)						->					List[str]:




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase)


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




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase)



   @slow
   def       UpperCAmelCase		(    self	:      str)						->					Union[str, Any]:




         """simple docstring"""

         lowercase__  =	TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge')
         self.assertIsNotNone(lowerCAmelCase)



@require_tf
class    UpperCAmelCase__(				unittest.TestCase						):

   '''simple docstring'''




   @unittest.skip(reason='Model not available yet')
   def       UpperCAmelCase		(    self	:      Union[str, Any])						->					Dict:




         """simple docstring"""

         pass



   @slow
   def       UpperCAmelCase		(    self	:      Optional[int])						->					Any:




         """simple docstring"""

         lowercase__  =	TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge')
         lowercase__  =	tf.constant([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]])
         lowercase__  =	tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
         lowercase__  =	model(lowerCAmelCase      ,					attention_mask=lowerCAmelCase)[0]

         lowercase__  =	tf.constant(
             [[[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]]])
         tf.debugging.assert_near(output[:, 1:4, 1:4]      ,					lowerCAmelCase      ,					atol=1E-4)





from datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching

def 	_lowerCAmelCase (    ):
      import os as original_os
      from os import path as original_path
      from os import rename as original_rename
      from os.path import dirname as original_dirname
      from os.path import join as original_join

      assert _test_patching.os is original_os
      assert _test_patching.path is original_path
      assert _test_patching.join is original_join

      assert _test_patching.renamed_os is original_os
      assert _test_patching.renamed_path is original_path
      assert _test_patching.renamed_join is original_join

      lowercase__  =	'__test_patch_submodule_mock__'
      with patch_submodule(_test_patching    ,	'os.path.join'    ,	A__						):
            # Every way to access os.path.join must be patched, and the rest must stay untouched

            # check os.path.join
            assert isinstance(_test_patching.os    ,	_PatchedModuleObj						)
            assert isinstance(_test_patching.os.path    ,	_PatchedModuleObj						)
            assert _test_patching.os.path.join is mock

            # check path.join
            assert isinstance(_test_patching.path    ,	_PatchedModuleObj						)
            assert _test_patching.path.join is mock

            # check join
            assert _test_patching.join is mock

            # check that the other attributes are untouched
            assert _test_patching.os.rename is original_rename
            assert _test_patching.path.dirname is original_dirname
            assert _test_patching.os.path.dirname is original_dirname

            # Even renamed modules or objects must be patched

            # check renamed_os.path.join
            assert isinstance(_test_patching.renamed_os    ,	_PatchedModuleObj						)
            assert isinstance(_test_patching.renamed_os.path    ,	_PatchedModuleObj						)
            assert _test_patching.renamed_os.path.join is mock

            # check renamed_path.join
            assert isinstance(_test_patching.renamed_path    ,	_PatchedModuleObj						)
            assert _test_patching.renamed_path.join is mock

            # check renamed_join
            assert _test_patching.renamed_join is mock

            # check that the other attributes are untouched
            assert _test_patching.renamed_os.rename is original_rename
            assert _test_patching.renamed_path.dirname is original_dirname
            assert _test_patching.renamed_os.path.dirname is original_dirname

      # check that everthing is back to normal when the patch is over

      assert _test_patching.os is original_os
      assert _test_patching.path is original_path
      assert _test_patching.join is original_join

      assert _test_patching.renamed_os is original_os
      assert _test_patching.renamed_path is original_path
      assert _test_patching.renamed_join is original_join

def 	_lowerCAmelCase (    ):
      assert _test_patching.open is open

      lowercase__  =	'__test_patch_submodule_builtin_mock__'
      # _test_patching has "open" in its globals
      assert _test_patching.open is open
      with patch_submodule(_test_patching    ,	'open'    ,	A__						):
            assert _test_patching.open is mock

      # check that everthing is back to normal when the patch is over

      assert _test_patching.open is open

def 	_lowerCAmelCase (    ):
      # pandas.read_csv is not present in _test_patching
      lowercase__  =	'__test_patch_submodule_missing_mock__'
      with patch_submodule(_test_patching    ,	'pandas.read_csv'    ,	A__						):
            pass

def 	_lowerCAmelCase (    ):
      # builtin should always be mocked even if they're not in the globals
      # in case they're loaded at one point
      lowercase__  =	'__test_patch_submodule_missing_builtin_mock__'
      # _test_patching doesn't have "len" in its globals
      assert getattr(_test_patching    ,	'len'    ,	A__						) is None
      with patch_submodule(_test_patching    ,	'len'    ,	A__						):
            assert _test_patching.len is mock
      assert _test_patching.len is len

def 	_lowerCAmelCase (    ):
      lowercase__  =	'__test_patch_submodule_start_and_stop_mock__'
      lowercase__  =	patch_submodule(_test_patching    ,	'open'    ,	A__						)
      assert _test_patching.open is open
      patch.start()
      assert _test_patching.open is mock
      patch.stop()
      assert _test_patching.open is open

def 	_lowerCAmelCase (    ):
      from os import rename as original_rename
      from os.path import dirname as original_dirname
      from os.path import join as original_join

      lowercase__  =	'__test_patch_submodule_successive_join__'
      lowercase__  =	'__test_patch_submodule_successive_dirname__'
      lowercase__  =	'__test_patch_submodule_successive_rename__'
      assert _test_patching.os.path.join is original_join
      assert _test_patching.os.path.dirname is original_dirname
      assert _test_patching.os.rename is original_rename

      with patch_submodule(_test_patching    ,	'os.path.join'    ,	A__						):
            with patch_submodule(_test_patching    ,	'os.rename'    ,	A__						):
                  with patch_submodule(_test_patching    ,	'os.path.dirname'    ,	A__						):
                        assert _test_patching.os.path.join is mock_join
                        assert _test_patching.os.path.dirname is mock_dirname
                        assert _test_patching.os.rename is mock_rename

    # try another order
      with patch_submodule(_test_patching    ,	'os.rename'    ,	A__						):
            with patch_submodule(_test_patching    ,	'os.path.join'    ,	A__						):
                  with patch_submodule(_test_patching    ,	'os.path.dirname'    ,	A__						):
                        assert _test_patching.os.path.join is mock_join
                        assert _test_patching.os.path.dirname is mock_dirname
                        assert _test_patching.os.rename is mock_rename

      assert _test_patching.os.path.join is original_join
      assert _test_patching.os.path.dirname is original_dirname
      assert _test_patching.os.rename is original_rename

def 	_lowerCAmelCase (    ):
      lowercase__  =	'__test_patch_submodule_doesnt_exist_mock__'
      with patch_submodule(_test_patching    ,	'__module_that_doesn_exist__.__attribute_that_doesn_exist__'    ,	A__						):
            pass
      with patch_submodule(_test_patching    ,	'os.__attribute_that_doesn_exist__'    ,	A__						):
            pass
