

'''simple docstring'''



import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__lowercase     :						Optional[int]	=     pytest.mark.integration


__lowercase     :						Dict	=     {'comet'}
__lowercase     :						Optional[int]	=     importlib.util.find_spec('fairseq') is not None

__lowercase     :						Tuple	=     {'code_eval'}
__lowercase     :						Tuple	=     os.name == 'nt'

__lowercase     :						List[Any]	=     {'bertscore', 'frugalscore', 'perplexity'}
__lowercase     :						str	=     importlib.util.find_spec('transformers') is not None






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       List[Any]       ):
					@wraps(_SCREAMING_SNAKE_CASE       )
					def wrapper(self				:       int						,				_SCREAMING_SNAKE_CASE				:       Any       ):
										if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
															self.skipTest('"test requires Fairseq"'       )
										else:
															test_case(self						,				_SCREAMING_SNAKE_CASE       )

					return wrapper






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       Optional[Any]       ):
					@wraps(_SCREAMING_SNAKE_CASE       )
					def wrapper(self				:       str						,				_SCREAMING_SNAKE_CASE				:       Union[str, Any]       ):
										if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
															self.skipTest('"test requires transformers"'       )
										else:
															test_case(self						,				_SCREAMING_SNAKE_CASE       )

					return wrapper






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       str       ):
					@wraps(_SCREAMING_SNAKE_CASE       )
					def wrapper(self				:       Optional[int]						,				_SCREAMING_SNAKE_CASE				:       Tuple       ):
										if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
															self.skipTest('"test not supported on Windows"'       )
										else:
															test_case(self						,				_SCREAMING_SNAKE_CASE       )

					return wrapper






def   lowerCamelCase							():
					__a      :	Union[str, Any]    =  [metric_dir.split(os.sep       )[-2] for metric_dir in glob.glob('./metrics/*/'       )]
					return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names() )
@for_all_test_methods(
    lowerCAmelCase_		,				lowerCAmelCase_		,				lowerCAmelCase_ )
@local
class 							__UpperCamelCase    (		parameterized.TestCase ):
	A_           =   {}
	A_           =   None




	@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'							)
	@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'							)
	def 				__UpperCAmelCase							(       self						,    __a							):

						'''simple docstring'''





						__a      :	List[Any]    =  '[...]'
						__a      :	Dict    =  importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join('metrics'						,    __a							)							).module_path							)
						__a      :	Union[str, Any]    =  datasets.load.import_main_class(metric_module.__name__						,    dataset=__a							)
						# check parameters
						__a      :	Optional[int]    =  inspect.signature(metric._compute							).parameters
						self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()							)							)  # no **kwargs
						# run doctest
						with self.patch_intensive_calls(__a						,    metric_module.__name__							):
											with self.use_local_metrics():
																try:
																					__a      :	Optional[Any]    =  doctest.testmod(__a						,    verbose=__a						,    raise_on_error=__a							)
																except doctest.UnexpectedException as e:
																					raise e.exc_info[1]  # raise the exception that doctest caught
						self.assertEqual(results.failed						,    0							)
						self.assertGreater(results.attempted						,    1							)




	@slow
	def 				__UpperCAmelCase							(       self						,    __a							):

						'''simple docstring'''





						__a      :	Dict    =  '[...]'
						__a      :	Optional[Any]    =  importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join('metrics'						,    __a							)							).module_path							)
						# run doctest
						with self.use_local_metrics():
											__a      :	List[str]    =  doctest.testmod(__a						,    verbose=__a						,    raise_on_error=__a							)
						self.assertEqual(results.failed						,    0							)
						self.assertGreater(results.attempted						,    1							)




	@contextmanager
	def 				__UpperCAmelCase							(       self						,    __a						,    __a							):

						'''simple docstring'''





						if metric_name in self.INTENSIVE_CALLS_PATCHER:
											with self.INTENSIVE_CALLS_PATCHER[metric_name](__a							):
																yield
						else:
											yield




	@contextmanager
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						def load_local_metric(__a						,    *__a						,    **__a							):
											return load_metric(os.path.join('metrics'						,    __a							)						,    *__a						,    **__a							)

						with patch('datasets.load_metric'							) as mock_load_metric:
											__a      :	int    =  load_local_metric
											yield





	@classmethod
	def 				__UpperCAmelCase							(       cls						,    __a							):

						'''simple docstring'''





						def wrapper(__a							):
											__a      :	Union[str, Any]    =  contextmanager(__a							)
											__a      :	int    =  patcher
											return patcher

						return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt'       )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       int       ):
					import tensorflow.compat.va as tf
					from bleurt.score import Predictor

					tf.flags.DEFINE_string('sv'						,				''						,				''       )  # handle pytest cli flags





					class 							__UpperCamelCase    (		lowerCAmelCase_ ):




						def 				__UpperCAmelCase							(       self						,    __a							):

											'''simple docstring'''





											assert len(input_dict['input_ids']							) == 2
											return np.array([1.03, 1.04]							)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
					with patch('bleurt.score._create_predictor'       ) as mock_create_predictor:
										__a      :	List[str]    =  MockedPredictor()
										yield






@LocalMetricTest.register_intensive_calls_patcher('bertscore'       )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       int       ):
					import torch

					def bert_cos_score_idf(_SCREAMING_SNAKE_CASE				:       List[str]						,				_SCREAMING_SNAKE_CASE				:       List[Any]						,				*_SCREAMING_SNAKE_CASE				:       Union[str, Any]						,				**_SCREAMING_SNAKE_CASE				:       Dict       ):
										return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE       )       )

					# mock get_model which is supposed to do download a bert model
					# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
					with patch('bert_score.scorer.get_model'       ), patch(
					    'bert_score.scorer.bert_cos_score_idf'       ) as mock_bert_cos_score_idf:
										__a      :	Dict    =  bert_cos_score_idf
										yield






@LocalMetricTest.register_intensive_calls_patcher('comet'       )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       List[str]       ):
					def load_from_checkpoint(_SCREAMING_SNAKE_CASE				:       Optional[int]       ):





										class 							__UpperCamelCase    :




											def 				__UpperCAmelCase							(       self						,    __a						,    *__a						,    **__a							):

																'''simple docstring'''





																assert len(__a							) == 2
																__a      :	Optional[int]    =  [0.19, 0.92]
																return scores, sum(__a							) / len(__a							)



										return Model()

					# mock load_from_checkpoint which is supposed to do download a bert model
					# mock load_from_checkpoint which is supposed to do download a bert model
					with patch('comet.download_model'       ) as mock_download_model:
										__a      :	Optional[Any]    =  None
										with patch('comet.load_from_checkpoint'       ) as mock_load_from_checkpoint:
															__a      :	Optional[int]    =  load_from_checkpoint
															yield






def   lowerCamelCase							():
					__a      :	int    =  load_metric(os.path.join('metrics'						,				'seqeval'       )       )
					__a      :	Tuple    =  'ERROR'
					__a      :	List[str]    =  F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
					with pytest.raises(_SCREAMING_SNAKE_CASE						,				match=re.escape(_SCREAMING_SNAKE_CASE       )       ):
										metric.compute(predictions=[]						,				references=[]						,				scheme=_SCREAMING_SNAKE_CASE       )







'''simple docstring'''



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 							__UpperCamelCase    (		lowerCAmelCase_ ):




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

						'''simple docstring'''





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




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





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

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

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

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

						__a      :	Optional[int]    =  self.get_config()

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




	def 				__UpperCAmelCase							(       self							):

						'''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 				__UpperCAmelCase							(       self						,    __a							):

						'''simple docstring'''





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




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a							):

						'''simple docstring'''





						__a      :	Dict    =  DebertaVaModel(config=__a							)
						model.to(__a							)
						model.eval()
						__a      :	Optional[int]    =  model(__a						,    attention_mask=__a						,    token_type_ids=__a							)[0]
						__a      :	str    =  model(__a						,    token_type_ids=__a							)[0]
						__a      :	Optional[int]    =  model(__a							)[0]

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




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a							):

						'''simple docstring'''





						__a      :	int    =  DebertaVaForMaskedLM(config=__a							)
						model.to(__a							)
						model.eval()
						__a      :	List[Any]    =  model(__a						,    attention_mask=__a						,    token_type_ids=__a						,    labels=__a							)

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




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a							):

						'''simple docstring'''





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




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a							):

						'''simple docstring'''





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




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a							):

						'''simple docstring'''





						__a      :	List[str]    =  DebertaVaForQuestionAnswering(config=__a							)
						model.to(__a							)
						model.eval()
						__a      :	str    =  model(
						    __a						,    attention_mask=__a						,    token_type_ids=__a						,    start_positions=__a						,    end_positions=__a						,    )
						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						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a						,    __a							):

						'''simple docstring'''





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





	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	int    =  self.prepare_config_and_inputs()
						(
						    (
						    __a
						)   ,    (
						    __a
						)   ,    (
						    __a
						)   ,    (
						    __a
						)   ,    (
						    __a
						)   ,    (
						    __a
						)   ,    (
						    __a
						)   ,    
						)      :	Dict    =  config_and_inputs
						__a      :	Optional[int]    =  {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
						return config, inputs_dict





@require_torch
class 							__UpperCamelCase    (		lowerCAmelCase_		,				lowerCAmelCase_		,				unittest.TestCase ):
	A_           =   (
	    (
	        DebertaVaModel,
	        DebertaVaForMaskedLM,
	        DebertaVaForSequenceClassification,
	        DebertaVaForTokenClassification,
	        DebertaVaForQuestionAnswering,
	        DebertaVaForMultipleChoice,
	    )
	    if is_torch_available()
	    else ()
	)
	A_           =   (
	    {
	        "feature-extraction": DebertaVaModel,
	        "fill-mask": DebertaVaForMaskedLM,
	        "question-answering": DebertaVaForQuestionAnswering,
	        "text-classification": DebertaVaForSequenceClassification,
	        "token-classification": DebertaVaForTokenClassification,
	        "zero-shot": DebertaVaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)

	A_           =   True
	A_           =   False
	A_           =   False
	A_           =   False
	A_           =   False




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Union[str, Any]    =  DebertaVaModelTester(self							)
						__a      :	List[str]    =  ConfigTester(self						,    config_class=__a						,    hidden_size=37							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						self.config_tester.run_common_tests()




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Optional[Any]    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_deberta_model(*__a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Dict    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_deberta_for_sequence_classification(*__a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	int    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_deberta_for_masked_lm(*__a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	List[Any]    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_deberta_for_question_answering(*__a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Tuple    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_deberta_for_token_classification(*__a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	List[str]    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_deberta_for_multiple_choice(*__a							)





	@slow
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__a      :	str    =  DebertaVaModel.from_pretrained(__a							)
											self.assertIsNotNone(__a							)





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




	@unittest.skip(reason='Model not available yet'							)
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						pass





	@slow
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Optional[int]    =  DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge'							)

						__a      :	Optional[Any]    =  torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]							)
						__a      :	str    =  torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
						with torch.no_grad():
											__a      :	int    =  model(__a						,    attention_mask=__a							)[0]
						# compare the actual values for a slice.
						__a      :	str    =  torch.tensor(
						    [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]							)
						self.assertTrue(torch.allclose(output[:, 1:4, 1:4]						,    __a						,    atol=1E-4							)						,    f"""{output[:, 1:4, 1:4]}"""							)



