





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 dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
    import torch

if is_torch_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm


lowercase      :       List[str]									=  logging.get_logger(__name__)





@dataclass
class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Optional[Any]         =  [
       '''no_inference''',
       '''no_cuda''',
       '''no_tpu''',
       '''no_speed''',
       '''no_memory''',
       '''no_env_print''',
       '''no_multi_process''',
   ]

   def __init__(					self					,  **lowercase)			->						Tuple:







          '''simple docstring'''

          for deprecated_arg in self.deprecated_args:
                 if deprecated_arg in kwargs:
                        a__						:	Union[str, Any] =				deprecated_arg[3:]
                        setattr(self					,  lowercase					,  not kwargs.pop(lowercase))
                        logger.warning(
                            F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or'
                            F' {positive_arg}={kwargs[positive_arg]}')

          a__						:	Union[str, Any] =				kwargs.pop('torchscript'					,  self.torchscript)
          a__						:	Tuple =				kwargs.pop('torch_xla_tpu_print_metrics'					,  self.torch_xla_tpu_print_metrics)
          a__						:	Tuple =				kwargs.pop('fp16_opt_level'					,  self.fpaa_opt_level)
          super().__init__(**lowercase)

   __A   :				bool         =  field(default=__UpperCAmelCase ,  metadata={'''help''': '''Trace the models using torchscript'''}	)
   __A   :				bool         =  field(default=__UpperCAmelCase ,  metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''}	)
   __A   :				str         =  field(
       default='''O1''' ,  metadata={
           '''help''': (
               '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. '''
               '''See details at https://nvidia.github.io/apex/amp.html'''
           )
       } ,  )

   @cached_property
   def 							__lowercase		(					self)			->						Tuple["torch.device", int]:







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          logger.info('PyTorch: setting up devices')
          if not self.cuda:
                 a__						:	List[str] =				torch.device('cpu')
                 a__						:	Optional[Any] =				0
          elif is_torch_tpu_available():
                 a__						:	List[str] =				xm.xla_device()
                 a__						:	Union[str, Any] =				0
          else:
                 a__						:	List[Any] =				torch.device('cuda' if torch.cuda.is_available() else 'cpu')
                 a__						:	Optional[int] =				torch.cuda.device_count()
          return device, n_gpu

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







          '''simple docstring'''

          return is_torch_tpu_available() and self.tpu

   @property
   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          # TODO(PVP): currently only single GPU is supported
          return torch.cuda.current_device()

   @property
   def 							__lowercase		(					self)			->						"torch.device":







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          return self._setup_devices[0]

   @property
   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          return self._setup_devices[1]

   @property
   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          return self.n_gpu > 0


