



from jiwer import compute_measures

import datasets


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

UpperCAmelCase_									=							"\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n"

UpperCAmelCase_									=							"\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> wer = datasets.load_metric(\"wer\")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n"





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





   def 	__lowerCAmelCase							(	self			):
         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''',
             ]       ,     )





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase=None       ,     _lowerCAmelCase=None       ,     _lowerCAmelCase=False			):
         if concatenate_texts:
               return compute_measures(_lowerCAmelCase       ,     _lowerCAmelCase			)["wer"]
         else:
               _lowerCAmelCase 			=  0
               _lowerCAmelCase 			=  0
               for prediction, reference in zip(_lowerCAmelCase       ,     _lowerCAmelCase			):
                     _lowerCAmelCase 			=  compute_measures(_lowerCAmelCase       ,     _lowerCAmelCase			)
                     incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                     total += measures["substitutions"] + measures["deletions"] + measures["hits"]
               return incorrect / total




import unittest

from transformers import MraConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_torch_available():
    import torch

    from transformers import (
        MraForMaskedLM,
        MraForMultipleChoice,
        MraForQuestionAnswering,
        MraForSequenceClassification,
        MraForTokenClassification,
        MraModel,
    )
    from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST





class 		UpperCAmelCase						:





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase=2       ,     _lowerCAmelCase=8       ,     _lowerCAmelCase=True       ,     _lowerCAmelCase=True       ,     _lowerCAmelCase=True       ,     _lowerCAmelCase=True       ,     _lowerCAmelCase=99       ,     _lowerCAmelCase=16       ,     _lowerCAmelCase=5       ,     _lowerCAmelCase=2       ,     _lowerCAmelCase=36       ,     _lowerCAmelCase="gelu"       ,     _lowerCAmelCase=0.0       ,     _lowerCAmelCase=0.0       ,     _lowerCAmelCase=512       ,     _lowerCAmelCase=16       ,     _lowerCAmelCase=2       ,     _lowerCAmelCase=0.02       ,     _lowerCAmelCase=3       ,     _lowerCAmelCase=4       ,     _lowerCAmelCase=None       ,     ):
         _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 			=  scope





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  ids_tensor([self.batch_size, self.seq_length]       ,     self.vocab_size			)

         _lowerCAmelCase 			=  None
         if self.use_input_mask:
               _lowerCAmelCase 			=  random_attention_mask([self.batch_size, self.seq_length]			)

         _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 	__lowerCAmelCase							(	self			):
         return MraConfig(
             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       ,     is_decoder=_lowerCAmelCase       ,     initializer_range=self.initializer_range       ,     )





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.get_config()
         _lowerCAmelCase 			=  300
         return config





   def 	__lowerCAmelCase							(	self			):
         (
             (
             _lowerCAmelCase
         )			,   (
             _lowerCAmelCase
         )			,   (
             _lowerCAmelCase
         )			,   (
             _lowerCAmelCase
         )			,   (
             _lowerCAmelCase
         )			,   (
             _lowerCAmelCase
         )			,   (
             _lowerCAmelCase
         )			,   
         ) 			=  self.prepare_config_and_inputs()

         _lowerCAmelCase 			=  True
         _lowerCAmelCase 			=  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]			)
         _lowerCAmelCase 			=  ids_tensor([self.batch_size, self.seq_length]       ,     vocab_size=2			)

         return (
             config,
             input_ids,
             token_type_ids,
             input_mask,
             sequence_labels,
             token_labels,
             choice_labels,
             encoder_hidden_states,
             encoder_attention_mask,
         )





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  MraModel(config=_lowerCAmelCase			)
         model.to(_lowerCAmelCase			)
         model.eval()
         _lowerCAmelCase 			=  model(_lowerCAmelCase       ,     attention_mask=_lowerCAmelCase       ,     token_type_ids=_lowerCAmelCase			)
         _lowerCAmelCase 			=  model(_lowerCAmelCase       ,     token_type_ids=_lowerCAmelCase			)
         _lowerCAmelCase 			=  model(_lowerCAmelCase			)
         self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)			)





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     ):
         _lowerCAmelCase 			=  True
         _lowerCAmelCase 			=  MraModel(_lowerCAmelCase			)
         model.to(_lowerCAmelCase			)
         model.eval()
         _lowerCAmelCase 			=  model(
             _lowerCAmelCase       ,     attention_mask=_lowerCAmelCase       ,     token_type_ids=_lowerCAmelCase       ,     encoder_hidden_states=_lowerCAmelCase       ,     encoder_attention_mask=_lowerCAmelCase       ,     )
         _lowerCAmelCase 			=  model(
             _lowerCAmelCase       ,     attention_mask=_lowerCAmelCase       ,     token_type_ids=_lowerCAmelCase       ,     encoder_hidden_states=_lowerCAmelCase       ,     )
         _lowerCAmelCase 			=  model(_lowerCAmelCase       ,     attention_mask=_lowerCAmelCase       ,     token_type_ids=_lowerCAmelCase			)
         self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)			)





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  MraForMaskedLM(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 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  MraForQuestionAnswering(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 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  self.num_labels
         _lowerCAmelCase 			=  MraForSequenceClassification(_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.num_labels)			)





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  self.num_labels
         _lowerCAmelCase 			=  MraForTokenClassification(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 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  self.num_choices
         _lowerCAmelCase 			=  MraForMultipleChoice(config=_lowerCAmelCase			)
         model.to(_lowerCAmelCase			)
         model.eval()
         _lowerCAmelCase 			=  input_ids.unsqueeze(1			).expand(-1       ,     self.num_choices       ,     -1			).contiguous()
         _lowerCAmelCase 			=  token_type_ids.unsqueeze(1			).expand(-1       ,     self.num_choices       ,     -1			).contiguous()
         _lowerCAmelCase 			=  input_mask.unsqueeze(1			).expand(-1       ,     self.num_choices       ,     -1			).contiguous()
         _lowerCAmelCase 			=  model(
             _lowerCAmelCase       ,     attention_mask=_lowerCAmelCase       ,     token_type_ids=_lowerCAmelCase       ,     labels=_lowerCAmelCase       ,     )
         self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_choices)			)





   def 	__lowerCAmelCase							(	self			):
         _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 		UpperCAmelCase						(						snake_case_       ,unittest.TestCase				):
   SCREAMING_SNAKE_CASE__							=     (
       (
           MraModel,
           MraForMaskedLM,
           MraForMultipleChoice,
           MraForQuestionAnswering,
           MraForSequenceClassification,
           MraForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   SCREAMING_SNAKE_CASE__							=     False
   SCREAMING_SNAKE_CASE__							=     False
   SCREAMING_SNAKE_CASE__							=     False
   SCREAMING_SNAKE_CASE__							=     False

   SCREAMING_SNAKE_CASE__							=     ()





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  MraModelTester(self			)
         _lowerCAmelCase 			=  ConfigTester(self       ,     config_class=_lowerCAmelCase       ,     hidden_size=37			)





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





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
               _lowerCAmelCase 			=  type
               self.model_tester.create_and_check_model(*_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_multiple_choice(*_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(*_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*_lowerCAmelCase			)





   @slow
   def 	__lowerCAmelCase							(	self			):
         for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowerCAmelCase 			=  MraModel.from_pretrained(_lowerCAmelCase			)
               self.assertIsNotNone(_lowerCAmelCase			)





   @unittest.skip(reason='''MRA does not output attentions'''			)
   def 	__lowerCAmelCase							(	self			):
         return






@require_torch
class 		UpperCAmelCase						(						unittest.TestCase				):





   @slow
   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  MraModel.from_pretrained('''uw-madison/mra-base-512-4'''			)
         _lowerCAmelCase 			=  torch.arange(256			).unsqueeze(0			)

         with torch.no_grad():
               _lowerCAmelCase 			=  model(_lowerCAmelCase			)[0]

         _lowerCAmelCase 			=  torch.Size((1, 256, 768)			)
         self.assertEqual(output.shape       ,     _lowerCAmelCase			)

         _lowerCAmelCase 			=  torch.tensor(
             [[[-0.0_140, 0.0_830, -0.0_381], [0.1_546, 0.1_402, 0.0_220], [0.1_162, 0.0_851, 0.0_165]]]			)

         self.assertTrue(torch.allclose(output[:, :3, :3]       ,     _lowerCAmelCase       ,     atol=1E-4			)			)





   @slow
   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4'''			)
         _lowerCAmelCase 			=  torch.arange(256			).unsqueeze(0			)

         with torch.no_grad():
               _lowerCAmelCase 			=  model(_lowerCAmelCase			)[0]

         _lowerCAmelCase 			=  50_265

         _lowerCAmelCase 			=  torch.Size((1, 256, vocab_size)			)
         self.assertEqual(output.shape       ,     _lowerCAmelCase			)

         _lowerCAmelCase 			=  torch.tensor(
             [[[9.2_595, -3.6_038, 11.8_819], [9.3_869, -3.2_693, 11.0_956], [11.8_524, -3.4_938, 13.1_210]]]			)

         self.assertTrue(torch.allclose(output[:, :3, :3]       ,     _lowerCAmelCase       ,     atol=1E-4			)			)





   @slow
   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3'''			)
         _lowerCAmelCase 			=  torch.arange(4_096			).unsqueeze(0			)

         with torch.no_grad():
               _lowerCAmelCase 			=  model(_lowerCAmelCase			)[0]

         _lowerCAmelCase 			=  50_265

         _lowerCAmelCase 			=  torch.Size((1, 4_096, vocab_size)			)
         self.assertEqual(output.shape       ,     _lowerCAmelCase			)

         _lowerCAmelCase 			=  torch.tensor(
             [[[5.4_789, -2.3_564, 7.5_064], [7.9_067, -1.3_369, 9.9_668], [9.0_712, -1.8_106, 7.0_380]]]			)

         self.assertTrue(torch.allclose(output[:, :3, :3]       ,     _lowerCAmelCase       ,     atol=1E-4			)			)