



from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
		from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType


__A       =						logging.get_logger(__name__)

__A       =						{
    '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''',
    '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''',
    '''microsoft/deberta-v2-xlarge-mnli''': (
        '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json'''
    ),
    '''microsoft/deberta-v2-xxlarge-mnli''': (
        '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json'''
    ),
}






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	a__				: Optional[int]		       =							"deberta-v2"




	def __init__(     self     :						Optional[Any]						,  __UpperCAmelCase     :						int=128_100						,  __UpperCAmelCase     :						Tuple=1_536						,  __UpperCAmelCase     :						Optional[int]=24						,  __UpperCAmelCase     :						Any=24						,  __UpperCAmelCase     :						List[Any]=6_144						,  __UpperCAmelCase     :						List[Any]="gelu"						,  __UpperCAmelCase     :						Optional[Any]=0.1						,  __UpperCAmelCase     :						str=0.1						,  __UpperCAmelCase     :						str=512						,  __UpperCAmelCase     :						Any=0						,  __UpperCAmelCase     :						List[Any]=0.02						,  __UpperCAmelCase     :						Optional[int]=1E-7						,  __UpperCAmelCase     :						Dict=False						,  __UpperCAmelCase     :						int=-1						,  __UpperCAmelCase     :						Optional[int]=0						,  __UpperCAmelCase     :						List[Any]=True						,  __UpperCAmelCase     :						int=None						,  __UpperCAmelCase     :						List[str]=0						,  __UpperCAmelCase     :						int="gelu"						,  **__UpperCAmelCase     :						Optional[int]						,  )      ->			int:
							super().__init__(**__UpperCAmelCase					)

							UpperCAmelCase_=       hidden_size
							UpperCAmelCase_=       num_hidden_layers
							UpperCAmelCase_=       num_attention_heads
							UpperCAmelCase_=       intermediate_size
							UpperCAmelCase_=       hidden_act
							UpperCAmelCase_=       hidden_dropout_prob
							UpperCAmelCase_=       attention_probs_dropout_prob
							UpperCAmelCase_=       max_position_embeddings
							UpperCAmelCase_=       type_vocab_size
							UpperCAmelCase_=       initializer_range
							UpperCAmelCase_=       relative_attention
							UpperCAmelCase_=       max_relative_positions
							UpperCAmelCase_=       pad_token_id
							UpperCAmelCase_=       position_biased_input

							# Backwards compatibility
							if type(__UpperCAmelCase					) == str:
													UpperCAmelCase_=       [x.strip() for x in pos_att_type.lower().split("""|"""					)]

							UpperCAmelCase_=       pos_att_type
							UpperCAmelCase_=       vocab_size
							UpperCAmelCase_=       layer_norm_eps

							UpperCAmelCase_=       kwargs.get("""pooler_hidden_size"""						,  __UpperCAmelCase					)
							UpperCAmelCase_=       pooler_dropout
							UpperCAmelCase_=       pooler_hidden_act






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	@property
	def   _SCREAMING_SNAKE_CASE		(     self     :						int					)      ->			Mapping[str, Mapping[int, str]]:
							if self.task == "multiple-choice":
													UpperCAmelCase_=       {0: """batch""", 1: """choice""", 2: """sequence"""}
							else:
													UpperCAmelCase_=       {0: """batch""", 1: """sequence"""}
							if self._config.type_vocab_size > 0:
													return OrderedDict(
													    [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)]					)
							else:
													return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)]					)




	@property
	def   _SCREAMING_SNAKE_CASE		(     self     :						List[Any]					)      ->			int:
							return 12




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[Any]						,  __UpperCAmelCase     :						Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]						,  __UpperCAmelCase     :						int = -1						,  __UpperCAmelCase     :						int = -1						,  __UpperCAmelCase     :						int = -1						,  __UpperCAmelCase     :						bool = False						,  __UpperCAmelCase     :						Optional["TensorType"] = None						,  __UpperCAmelCase     :						int = 3						,  __UpperCAmelCase     :						int = 40						,  __UpperCAmelCase     :						int = 40						,  __UpperCAmelCase     :						"PreTrainedTokenizerBase" = None						,  )      ->			Mapping[str, Any]:
							UpperCAmelCase_=       super().generate_dummy_inputs(preprocessor=__UpperCAmelCase						,  framework=__UpperCAmelCase					)
							if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
													del dummy_inputs["token_type_ids"]
							return dummy_inputs









import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


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






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	def __init__(     self     :						Any						,  *__UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]=None						,  __UpperCAmelCase     :						Optional[int]=None						,  **__UpperCAmelCase     :						Dict					)      ->			Optional[int]:
							super().__init__(*__UpperCAmelCase						,  **__UpperCAmelCase					)
							UpperCAmelCase_=       eval_examples
							UpperCAmelCase_=       post_process_function




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple						,  __UpperCAmelCase     :						Optional[Dataset] = None						,  __UpperCAmelCase     :						Optional[Any]=None						,  __UpperCAmelCase     :						Optional[List[str]] = None						,  __UpperCAmelCase     :						str = "eval"						,  **__UpperCAmelCase     :						Any						,  )      ->			Dict[str, float]:
							UpperCAmelCase_=       gen_kwargs.copy()
							UpperCAmelCase_=       (
							    gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length"""					) is not None else self.args.generation_max_length
							)
							UpperCAmelCase_=       (
							    gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams"""					) is not None else self.args.generation_num_beams
							)
							UpperCAmelCase_=       gen_kwargs

							UpperCAmelCase_=       self.eval_dataset if eval_dataset is None else eval_dataset
							UpperCAmelCase_=       self.get_eval_dataloader(__UpperCAmelCase					)
							UpperCAmelCase_=       self.eval_examples if eval_examples is None else eval_examples

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Evaluation"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics
							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)

							if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
													# Only the main node write the results by default
													UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase					)
													UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

													# Prefix all keys with metric_key_prefix + '_'
													for key in list(metrics.keys()					):
																			if not key.startswith(F"""{metric_key_prefix}_"""					):
																									UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)

													metrics.update(output.metrics					)
							else:
													UpperCAmelCase_=       output.metrics

							if self.args.should_log:
													# Only the main node log the results by default
													self.log(__UpperCAmelCase					)

							if self.args.tpu_metrics_debug or self.args.debug:
													# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
													xm.master_print(met.metrics_report()					)

							UpperCAmelCase_=       self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  __UpperCAmelCase					)
							return metrics




	def   _SCREAMING_SNAKE_CASE		(     self     :						int						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[int]=None						,  __UpperCAmelCase     :						str = "test"						,  **__UpperCAmelCase     :						List[str]					)      ->			Tuple:
							UpperCAmelCase_=       gen_kwargs.copy()

							UpperCAmelCase_=       self.get_test_dataloader(__UpperCAmelCase					)

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Prediction"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics

							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)
							if self.post_process_function is None or self.compute_metrics is None:
													return output

							UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase						,  """predict"""					)
							UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()					):
													if not key.startswith(F"""{metric_key_prefix}_"""					):
																			UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)
							metrics.update(output.metrics					)
							return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=__UpperCAmelCase					)




