


'''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     lowercase__  (						__UpperCAmelCase					):





							'''simple docstring'''


							def __init__(    self    ,					__snake_case    ,					__snake_case=13    ,					__snake_case=7    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=99    ,					__snake_case=32    ,					__snake_case=5    ,					__snake_case=4    ,					__snake_case=37    ,					__snake_case="gelu"    ,					__snake_case=0.1    ,					__snake_case=0.1    ,					__snake_case=512    ,					__snake_case=16    ,					__snake_case=2    ,					__snake_case=0.02    ,					__snake_case=False    ,					__snake_case=True    ,					__snake_case="None"    ,					__snake_case=3    ,					__snake_case=4    ,					__snake_case=None    ,					):
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      parent
											_SCREAMING_SNAKE_CASE :       List[str]     		=      batch_size
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      seq_length
											_SCREAMING_SNAKE_CASE :       Any     		=      is_training
											_SCREAMING_SNAKE_CASE :       Tuple     		=      use_input_mask
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      use_token_type_ids
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      use_labels
											_SCREAMING_SNAKE_CASE :       int     		=      vocab_size
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      hidden_size
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      num_hidden_layers
											_SCREAMING_SNAKE_CASE :       Any     		=      num_attention_heads
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      intermediate_size
											_SCREAMING_SNAKE_CASE :       Any     		=      hidden_act
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      hidden_dropout_prob
											_SCREAMING_SNAKE_CASE :       int     		=      attention_probs_dropout_prob
											_SCREAMING_SNAKE_CASE :       Tuple     		=      max_position_embeddings
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      type_vocab_size
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      type_sequence_label_size
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      initializer_range
											_SCREAMING_SNAKE_CASE :       List[str]     		=      num_labels
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      num_choices
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      relative_attention
											_SCREAMING_SNAKE_CASE :       List[str]     		=      position_biased_input
											_SCREAMING_SNAKE_CASE :       List[str]     		=      pos_att_type
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      scope






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

											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      None
											if self.use_input_mask:
															_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      ids_tensor([self.batch_size, self.seq_length]    ,					vocab_size=2  )

											_SCREAMING_SNAKE_CASE :       Dict     		=      None
											if self.use_token_type_ids:
															_SCREAMING_SNAKE_CASE :       List[Any]     		=      ids_tensor([self.batch_size, self.seq_length]    ,					self.type_vocab_size  )

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

											_SCREAMING_SNAKE_CASE :       Dict     		=      self.get_config()

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






							def UpperCAmelCase_	(    self  ):
											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    ,					__snake_case  ):
											self.parent.assertListEqual(list(result.loss.size()  )    ,					[]  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       List[str]     		=      DebertaVaModel(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      model(__snake_case    ,					attention_mask=__snake_case    ,					token_type_ids=__snake_case  )[0]
											_SCREAMING_SNAKE_CASE :       str     		=      model(__snake_case    ,					token_type_ids=__snake_case  )[0]
											_SCREAMING_SNAKE_CASE :       Tuple     		=      model(__snake_case  )[0]

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






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       Dict     		=      DebertaVaForMaskedLM(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       str     		=      model(__snake_case    ,					attention_mask=__snake_case    ,					token_type_ids=__snake_case    ,					labels=__snake_case  )

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






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






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      self.num_labels
											_SCREAMING_SNAKE_CASE :       Dict     		=      DebertaVaForTokenClassification(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       str     		=      model(__snake_case    ,					attention_mask=__snake_case    ,					token_type_ids=__snake_case    ,					labels=__snake_case  )
											self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.seq_length, self.num_labels)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       Dict     		=      DebertaVaForQuestionAnswering(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       Any     		=      model(
											    __snake_case    ,					attention_mask=__snake_case    ,					token_type_ids=__snake_case    ,					start_positions=__snake_case    ,					end_positions=__snake_case    ,					)
											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    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       Dict     		=      DebertaVaForMultipleChoice(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       Any     		=      input_ids.unsqueeze(1  ).expand(-1    ,					self.num_choices    ,					-1  ).contiguous()
											_SCREAMING_SNAKE_CASE :       int     		=      token_type_ids.unsqueeze(1  ).expand(-1    ,					self.num_choices    ,					-1  ).contiguous()
											_SCREAMING_SNAKE_CASE :       int     		=      input_mask.unsqueeze(1  ).expand(-1    ,					self.num_choices    ,					-1  ).contiguous()
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      model(
											    __snake_case    ,					attention_mask=__snake_case    ,					token_type_ids=__snake_case    ,					labels=__snake_case    ,					)
											self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.num_choices)  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      self.prepare_config_and_inputs()
											(
											    _SCREAMING_SNAKE_CASE							
											) :       Optional[int]     		=      config_and_inputs
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
											return config, inputs_dict





@require_torch
class     lowercase__  (						__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 UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       int     		=      DebertaVaModelTester(self  )
											_SCREAMING_SNAKE_CASE :       Dict     		=      ConfigTester(self    ,					config_class=__snake_case    ,					hidden_size=37  )






							def UpperCAmelCase_	(    self  ):
											self.config_tester.run_common_tests()






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       str     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_deberta_model(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_deberta_for_sequence_classification(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_deberta_for_masked_lm(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       str     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_deberta_for_question_answering(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_deberta_for_token_classification(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       int     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_deberta_for_multiple_choice(*__snake_case  )






							@slow
							def UpperCAmelCase_	(    self  ):

											for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE :       List[Any]     		=      DebertaVaModel.from_pretrained(__snake_case  )
															self.assertIsNotNone(__snake_case  )





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





							'''simple docstring'''


							@unittest.skip(reason="""Model not available yet"""  )
							def UpperCAmelCase_	(    self  ):
											pass






							@slow
							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Any     		=      DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge"""  )

											_SCREAMING_SNAKE_CASE :       int     		=      torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]  )
											with torch.no_grad():
															_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      model(__snake_case    ,					attention_mask=__snake_case  )[0]
											# compare the actual values for a slice.
											_SCREAMING_SNAKE_CASE :       int     		=      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]    ,					__snake_case    ,					atol=1e-4  )    ,					f"""{output[:, 1:4, 1:4]}"""  )











from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse("""3.8"""):
    import importlib_metadata
else:
    import importlib.metadata as importlib_metadata


lowercase      :       Tuple									=  """"""


if version.parse(importlib_metadata.version("""jiwer""")) < version.parse("""2.3.0"""):





    class  A__    (							tr.AbstractTransform	):




       """simple docstring"""



       def __init__(					self					,  lowercase = " ")			->						Tuple:







              '''simple docstring'''

              a__						:	Tuple =				sentence_delimiter

       def 							__lowercase		(					self					,  lowercase)			->						Optional[int]:







              '''simple docstring'''

              return list(lowercase)

       def 							__lowercase		(					self					,  lowercase)			->						Dict:







              '''simple docstring'''

              a__						:	Tuple =				[]
              for sent_idx, sentence in enumerate(lowercase):
                     chars.extend(self.process_string(lowercase))
                     if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowercase) - 1:
                            chars.append(self.sentence_delimiter)
              return chars

    lowercase      :       Union[str, Any]									=  tr.Compose(
        [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
    )
else:
    lowercase      :       List[str]									=  tr.Compose(
        [
            tr.RemoveMultipleSpaces(),
            tr.Strip(),
            tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
            tr.ReduceToListOfListOfChars(),
        ]
    )


lowercase      :       List[Any]									=  """\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
"""

lowercase      :       Optional[int]									=  """\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER's output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
"""

lowercase      :       Optional[Any]									=  """
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> cer = datasets.load_metric(\"cer\")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
"""





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,  _KWARGS_DESCRIPTION	)
class  A__    (							datasets.Metric	):




   """simple docstring"""



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







          '''simple docstring'''

          return datasets.MetricInfo(
              description=_DESCRIPTION					,  citation=_CITATION					,  inputs_description=_KWARGS_DESCRIPTION					,  features=datasets.Features(
                  {
                      'predictions': datasets.Value('string'					,  id='sequence'),
                      'references': datasets.Value('string'					,  id='sequence'),
                  })					,  codebase_urls=['https://github.com/jitsi/jiwer/']					,  reference_urls=[
                  'https://en.wikipedia.org/wiki/Word_error_rate',
                  'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates',
              ]					,  )

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase=False)			->						Any:







          '''simple docstring'''

          if concatenate_texts:
                 return jiwer.compute_measures(
                     lowercase					,  lowercase					,  truth_transform=lowercase					,  hypothesis_transform=lowercase					,  )["wer"]

          a__						:	Optional[int] =				0
          a__						:	str =				0
          for prediction, reference in zip(lowercase					,  lowercase):
                 a__						:	Optional[int] =				jiwer.compute_measures(
                     lowercase					,  lowercase					,  truth_transform=lowercase					,  hypothesis_transform=lowercase					,  )
                 incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                 total += measures["substitutions"] + measures["deletions"] + measures["hits"]

          return incorrect / total


