




from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
					import tensorflow as tf


__A        =    logging.get_logger(__name__)







@dataclass
class     __lowerCAmelCase (       __magic_name__ ):

			"""simple docstring"""







			snake_case_   		=       [
			    '''no_inference''',
			    '''no_cuda''',
			    '''no_tpu''',
			    '''no_speed''',
			    '''no_memory''',
			    '''no_env_print''',
			    '''no_multi_process''',
			]


			def __init__(      self			,						**lowerCamelCase__							)    ->      int:



							'''simple docstring'''
							for deprecated_arg in self.deprecated_args:
											if deprecated_arg in kwargs:
															__lowerCamelCase		       =    deprecated_arg[3:]
															__lowerCamelCase		       =    not kwargs.pop(lowerCamelCase__							)
															logger.warning(
															    f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"""
															    f""" {positive_arg}={kwargs[positive_arg]}"""							)
							__lowerCamelCase		       =    kwargs.pop('tpu_name'			,						self.tpu_name							)
							__lowerCamelCase		       =    kwargs.pop('device_idx'			,						self.device_idx							)
							__lowerCamelCase		       =    kwargs.pop('eager_mode'			,						self.eager_mode							)
							__lowerCamelCase		       =    kwargs.pop('use_xla'			,						self.use_xla							)
							super().__init__(**lowerCamelCase__							)

			snake_case_   		=       field(
			    default=__magic_name__			,				metadata={'''help''': '''Name of TPU'''}			,				)
			snake_case_   		=       field(
			    default=0			,				metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''}			,				)
			snake_case_   		=       field(default=__magic_name__			,				metadata={'''help''': '''Benchmark models in eager model.'''} )
			snake_case_   		=       field(
			    default=__magic_name__			,				metadata={
			        '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
			    }			,				)


			@cached_property
			def       lowercase_    (      self							)    ->      Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]:



							'''simple docstring'''
							requires_backends(self			,						['tf']							)
							__lowerCamelCase		       =    None
							if self.tpu:
											try:
															if self.tpu_name:
																			__lowerCamelCase		       =    tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name							)
															else:
																			__lowerCamelCase		       =    tf.distribute.cluster_resolver.TPUClusterResolver()
											except ValueError:
															__lowerCamelCase		       =    None
							return tpu


			@cached_property
			def       lowercase_    (      self							)    ->      Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]:



							'''simple docstring'''
							requires_backends(self			,						['tf']							)
							if self.is_tpu:
											tf.config.experimental_connect_to_cluster(self._setup_tpu							)
											tf.tpu.experimental.initialize_tpu_system(self._setup_tpu							)

											__lowerCamelCase		       =    tf.distribute.TPUStrategy(self._setup_tpu							)
							else:
											# currently no multi gpu is allowed
											if self.is_gpu:
															# TODO: Currently only single GPU is supported
															tf.config.set_visible_devices(self.gpu_list[self.device_idx]			,						'GPU'							)
															__lowerCamelCase		       =    tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}"""							)
											else:
															tf.config.set_visible_devices([]			,						'GPU'							)  # disable GPU
															__lowerCamelCase		       =    tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}"""							)

							return strategy


			@property
			def       lowercase_    (      self							)    ->      bool:



							'''simple docstring'''
							requires_backends(self			,						['tf']							)
							return self._setup_tpu is not None


			@property
			def       lowercase_    (      self							)    ->      "tf.distribute.Strategy":



							'''simple docstring'''
							requires_backends(self			,						['tf']							)
							return self._setup_strategy


			@property
			def       lowercase_    (      self							)    ->      Any:



							'''simple docstring'''
							requires_backends(self			,						['tf']							)
							return tf.config.list_physical_devices('GPU'							)


			@property
			def       lowercase_    (      self							)    ->      int:



							'''simple docstring'''
							requires_backends(self			,						['tf']							)
							if self.cuda:
											return len(self.gpu_list							)
							return 0






			@property
			def       lowercase_    (      self							)    ->      bool:



							'''simple docstring'''
							return self.n_gpu > 0








import unittest

from transformers import DebertaConfig, 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 (
					    DebertaForMaskedLM,
					    DebertaForQuestionAnswering,
					    DebertaForSequenceClassification,
					    DebertaForTokenClassification,
					    DebertaModel,
					)
					from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST







class     __lowerCAmelCase (       __magic_name__ ):

			"""simple docstring"""







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



							'''simple docstring'''
							__lowerCamelCase		       =    parent
							__lowerCamelCase		       =    batch_size
							__lowerCamelCase		       =    seq_length
							__lowerCamelCase		       =    is_training
							__lowerCamelCase		       =    use_input_mask
							__lowerCamelCase		       =    use_token_type_ids
							__lowerCamelCase		       =    use_labels
							__lowerCamelCase		       =    vocab_size
							__lowerCamelCase		       =    hidden_size
							__lowerCamelCase		       =    num_hidden_layers
							__lowerCamelCase		       =    num_attention_heads
							__lowerCamelCase		       =    intermediate_size
							__lowerCamelCase		       =    hidden_act
							__lowerCamelCase		       =    hidden_dropout_prob
							__lowerCamelCase		       =    attention_probs_dropout_prob
							__lowerCamelCase		       =    max_position_embeddings
							__lowerCamelCase		       =    type_vocab_size
							__lowerCamelCase		       =    type_sequence_label_size
							__lowerCamelCase		       =    initializer_range
							__lowerCamelCase		       =    num_labels
							__lowerCamelCase		       =    num_choices
							__lowerCamelCase		       =    relative_attention
							__lowerCamelCase		       =    position_biased_input
							__lowerCamelCase		       =    pos_att_type
							__lowerCamelCase		       =    scope


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size							)

							__lowerCamelCase		       =    None
							if self.use_input_mask:
											__lowerCamelCase		       =    ids_tensor([self.batch_size, self.seq_length]			,						vocab_size=2							)

							__lowerCamelCase		       =    None
							if self.use_token_type_ids:
											__lowerCamelCase		       =    ids_tensor([self.batch_size, self.seq_length]			,						self.type_vocab_size							)

							__lowerCamelCase		       =    None
							__lowerCamelCase		       =    None
							__lowerCamelCase		       =    None
							if self.use_labels:
											__lowerCamelCase		       =    ids_tensor([self.batch_size]			,						self.type_sequence_label_size							)
											__lowerCamelCase		       =    ids_tensor([self.batch_size, self.seq_length]			,						self.num_labels							)
											__lowerCamelCase		       =    ids_tensor([self.batch_size]			,						self.num_choices							)

							__lowerCamelCase		       =    self.get_config()

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


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



							'''simple docstring'''
							return DebertaConfig(
							    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							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.get_config()
							__lowerCamelCase		       =    300
							return config


			def       lowercase_    (      self			,						lowerCamelCase__							)    ->      Optional[int]:



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


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaModel(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__							)[0]
							__lowerCamelCase		       =    model(lowerCamelCase__			,						token_type_ids=lowerCamelCase__							)[0]
							__lowerCamelCase		       =    model(lowerCamelCase__							)[0]

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


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaForMaskedLM(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						labels=lowerCamelCase__							)

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


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.num_labels
							__lowerCamelCase		       =    DebertaForSequenceClassification(lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						labels=lowerCamelCase__							)
							self.parent.assertListEqual(list(result.logits.size()							)			,						[self.batch_size, self.num_labels]							)
							self.check_loss_output(lowerCamelCase__							)


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.num_labels
							__lowerCamelCase		       =    DebertaForTokenClassification(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						labels=lowerCamelCase__							)
							self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.num_labels)							)


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaForQuestionAnswering(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(
							    lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						start_positions=lowerCamelCase__			,						end_positions=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       lowercase_    (      self							)    ->      Union[str, Any]:



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







@require_torch
class     __lowerCAmelCase (       __magic_name__			,				__magic_name__			,				unittest.TestCase ):

			"""simple docstring"""







			snake_case_   		=       (
			    (
			        DebertaModel,
			        DebertaForMaskedLM,
			        DebertaForSequenceClassification,
			        DebertaForTokenClassification,
			        DebertaForQuestionAnswering,
			    )
			    if is_torch_available()
			    else ()
			)
			snake_case_   		=       (
			    {
			        '''feature-extraction''': DebertaModel,
			        '''fill-mask''': DebertaForMaskedLM,
			        '''question-answering''': DebertaForQuestionAnswering,
			        '''text-classification''': DebertaForSequenceClassification,
			        '''token-classification''': DebertaForTokenClassification,
			        '''zero-shot''': DebertaForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)

			snake_case_   		=       True
			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False


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



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaModelTester(self							)
							__lowerCamelCase		       =    ConfigTester(self			,						config_class=lowerCamelCase__			,						hidden_size=37							)


			def       lowercase_    (      self							)    ->      Optional[int]:



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


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_model(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCamelCase__							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_question_answering(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_token_classification(*lowerCamelCase__							)






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



							'''simple docstring'''
							for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase		       =    DebertaModel.from_pretrained(lowerCamelCase__							)
											self.assertIsNotNone(lowerCamelCase__							)







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

			"""simple docstring"""







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



							'''simple docstring'''
							pass






			@slow
			def       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaModel.from_pretrained('microsoft/deberta-base'							)

							__lowerCamelCase		       =    torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]							)
							__lowerCamelCase		       =    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
							with torch.no_grad():
											__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__							)[0]
							# compare the actual values for a slice.
							__lowerCamelCase		       =    torch.tensor(
							    [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]]							)
							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]			,						lowerCamelCase__			,						atol=1e-4							)			,						f"""{output[:, 1:4, 1:4]}"""							)


