


import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
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 MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
 from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder



def        UpperCamelCase_(   lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_=None							,				lowerCamelCase_=None							,				lowerCamelCase_=None							,				lowerCamelCase_=None							,				lowerCamelCase_=None							,				)					->		Any:
    if attention_mask is None:
        _lowercase :							Optional[int]   	=	input_ids.ne(config.pad_token_id				)
    if decoder_attention_mask is None:
        _lowercase :							Dict   	=	decoder_input_ids.ne(config.pad_token_id				)
    if head_mask is None:
        _lowercase :							int   	=	torch.ones(config.encoder_layers							,				config.encoder_attention_heads							,				device=lowerCamelCase_				)
    if decoder_head_mask is None:
        _lowercase :							List[Any]   	=	torch.ones(config.decoder_layers							,				config.decoder_attention_heads							,				device=lowerCamelCase_				)
    if cross_attn_head_mask is None:
        _lowercase :							str   	=	torch.ones(config.decoder_layers							,				config.decoder_attention_heads							,				device=lowerCamelCase_				)
    return {
        "input_ids": input_ids,
        "decoder_input_ids": decoder_input_ids,
        "attention_mask": attention_mask,
        "decoder_attention_mask": attention_mask,
        "head_mask": head_mask,
        "decoder_head_mask": decoder_head_mask,
        "cross_attn_head_mask": cross_attn_head_mask,
    }






class _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=13,   lowerCamelCase=7,   lowerCamelCase=True,   lowerCamelCase=False,   lowerCamelCase=99,   lowerCamelCase=16,   lowerCamelCase=2,   lowerCamelCase=4,   lowerCamelCase=4,   lowerCamelCase="relu",   lowerCamelCase=0.1,   lowerCamelCase=0.1,   lowerCamelCase=0.0,   lowerCamelCase=0.0,   lowerCamelCase=20,   lowerCamelCase=2,   lowerCamelCase=1,   lowerCamelCase=0,   ) ->     List[Any]:




           """simple docstring"""

           _lowercase :							int   	=	parent
           _lowercase :							str   	=	batch_size
           _lowercase :							Tuple   	=	seq_length
           _lowercase :							List[Any]   	=	is_training
           _lowercase :							Optional[Any]   	=	use_labels
           _lowercase :							Optional[Any]   	=	vocab_size
           _lowercase :							Any   	=	hidden_size
           _lowercase :							str   	=	num_hidden_layers
           _lowercase :							Tuple   	=	num_attention_heads
           _lowercase :							List[Any]   	=	intermediate_size
           _lowercase :							str   	=	hidden_act
           _lowercase :							Optional[int]   	=	hidden_dropout_prob
           _lowercase :							Dict   	=	attention_probs_dropout_prob
           _lowercase :							str   	=	encoder_layerdrop
           _lowercase :							str   	=	decoder_layerdrop
           _lowercase :							Any   	=	max_position_embeddings
           _lowercase :							Union[str, Any]   	=	eos_token_id
           _lowercase :							Dict   	=	pad_token_id
           _lowercase :							Any   	=	bos_token_id
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							Dict   	=	ids_tensor([self.batch_size, self.seq_length],   self.vocab_size)
           _lowercase :							int   	=	self.eos_token_id  # Eos Token
           _lowercase :							int   	=	ids_tensor([self.batch_size, self.seq_length],   self.vocab_size)

           # we need to clamp the input ids here to avoid having pad token in between
           # this is because for M2M100 the position_ids are prepared such that
           # all pad tokens have pos id = 2 and rest are between 2..seq_length
           # and the seq_length here is seq_length - num_pad_tokens
           # but when using past, there is no way of knowing if the past input ids had
           # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
           # position_ids being off by num_pad_tokens in past input
           _lowercase :							Dict   	=	input_ids.clamp(self.pad_token_id + 1)
           _lowercase :							Union[str, Any]   	=	decoder_input_ids.clamp(self.pad_token_id + 1)

           _lowercase :							List[Any]   	=	self.get_config()
           _lowercase :							int   	=	prepare_mam_aaa_inputs_dict(lowerCamelCase,   lowerCamelCase,   lowerCamelCase)
           return config, inputs_dict
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           return MaMaaaConfig(
               vocab_size=self.vocab_size,   d_model=self.hidden_size,   encoder_layers=self.num_hidden_layers,   decoder_layers=self.num_hidden_layers,   encoder_attention_heads=self.num_attention_heads,   decoder_attention_heads=self.num_attention_heads,   encoder_ffn_dim=self.intermediate_size,   decoder_ffn_dim=self.intermediate_size,   dropout=self.hidden_dropout_prob,   attention_dropout=self.attention_probs_dropout_prob,   encoder_layerdrop=self.encoder_layerdrop,   decoder_layerdrop=self.decoder_layerdrop,   max_position_embeddings=self.max_position_embeddings,   eos_token_id=self.eos_token_id,   bos_token_id=self.bos_token_id,   pad_token_id=self.pad_token_id,   )
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           _lowercase	,       _lowercase :							List[str]   	=	self.prepare_config_and_inputs()
           return config, inputs_dict
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	MaMaaaModel(config=lowerCamelCase).get_decoder().to(lowerCamelCase).eval()
           _lowercase :							Any   	=	inputs_dict['input_ids']
           _lowercase :							Any   	=	inputs_dict['attention_mask']
           _lowercase :							Dict   	=	inputs_dict['head_mask']

           # first forward pass
           _lowercase :							int   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   head_mask=lowerCamelCase,   use_cache=lowerCamelCase)

           _lowercase	,       _lowercase :							Optional[Any]   	=	outputs.to_tuple()

           # create hypothetical multiple next token and extent to next_input_ids
           _lowercase :							Dict   	=	ids_tensor((self.batch_size, 3),   config.vocab_size)
           _lowercase :							Dict   	=	ids_tensor((self.batch_size, 3),   2)

           # append to next input_ids and
           _lowercase :							Dict   	=	torch.cat([input_ids, next_tokens],   dim=-1)
           _lowercase :							Tuple   	=	torch.cat([attention_mask, next_attn_mask],   dim=-1)

           _lowercase :							int   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase)['last_hidden_state']
           _lowercase :							Any   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   past_key_values=lowerCamelCase)[
               'last_hidden_state'
           ]

           # select random slice
           _lowercase :							Optional[int]   	=	ids_tensor((1,),   output_from_past.shape[-1]).item()
           _lowercase :							Tuple   	=	output_from_no_past[:, -3:, random_slice_idx].detach()
           _lowercase :							Dict   	=	output_from_past[:, :, random_slice_idx].detach()

           self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

           # test that outputs are equal for slice
           self.parent.assertTrue(torch.allclose(lowerCamelCase,   lowerCamelCase,   atol=1E-2))




       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Dict   	=	MaMaaaModel(config=lowerCamelCase).to(lowerCamelCase).eval()
           _lowercase :							Dict   	=	model(**lowerCamelCase)

           _lowercase :							List[Any]   	=	outputs.encoder_last_hidden_state
           _lowercase :							Optional[int]   	=	outputs.last_hidden_state

           with tempfile.TemporaryDirectory() as tmpdirname:
               _lowercase :							Tuple   	=	model.get_encoder()
               encoder.save_pretrained(lowerCamelCase)
               _lowercase :							str   	=	MaMaaaEncoder.from_pretrained(lowerCamelCase).to(lowerCamelCase)

           _lowercase :							Dict   	=	encoder(inputs_dict['input_ids'],   attention_mask=inputs_dict['attention_mask'])[
               0
           ]

           self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3)

           with tempfile.TemporaryDirectory() as tmpdirname:
               _lowercase :							Dict   	=	model.get_decoder()
               decoder.save_pretrained(lowerCamelCase)
               _lowercase :							Union[str, Any]   	=	MaMaaaDecoder.from_pretrained(lowerCamelCase).to(lowerCamelCase)

           _lowercase :							Any   	=	decoder(
               input_ids=inputs_dict['decoder_input_ids'],   attention_mask=inputs_dict['decoder_attention_mask'],   encoder_hidden_states=lowerCamelCase,   encoder_attention_mask=inputs_dict['attention_mask'],   )[0]

           self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3)






@require_torch
class _lowerCamelCase(		_a,				_a,				_a,				unittest.TestCase     ):
       lowercase_				:			Optional[int]									=    (
           (
               MaMaaaModel,
               MaMaaaForConditionalGeneration,
           )
           if is_torch_available()
           else ()
       )
       lowercase_				:			int									=    (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
       lowercase_				:			str									=    (
           {
               """conversational""": MaMaaaForConditionalGeneration,
               """feature-extraction""": MaMaaaModel,
               """summarization""": MaMaaaForConditionalGeneration,
               """text2text-generation""": MaMaaaForConditionalGeneration,
               """translation""": MaMaaaForConditionalGeneration,
           }
           if is_torch_available()
           else {}
       )
       lowercase_				:			Dict									=    True
       lowercase_				:			List[Any]									=    True
       lowercase_				:			Any									=    False
       lowercase_				:			Any									=    False
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     List[Any]:




           """simple docstring"""

           if pipeline_test_casse_name == "TranslationPipelineTests":
               # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
               # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
               return True

           return False
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	MaMaaaModelTester(self)
           _lowercase :							str   	=	ConfigTester(self,   config_class=lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase	,       _lowercase :							Dict   	=	self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
               _lowercase :							Optional[Any]   	=	model_class(lowerCamelCase)

               with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_pretrained(lowerCamelCase)
                   _lowercase	,       _lowercase :							List[str]   	=	model_class.from_pretrained(lowerCamelCase,   output_loading_info=lowerCamelCase)
               self.assertEqual(info['missing_keys'],   [])
       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							List[str]   	=	self.model_tester.prepare_config_and_inputs_for_common()
           self.model_tester.check_encoder_decoder_model_standalone(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase	,       _lowercase :							Optional[Any]   	=	self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
               _lowercase :							Any   	=	model_class(lowerCamelCase)
               model.to(lowerCamelCase)
               model.eval()

               _lowercase :							List[Any]   	=	copy.deepcopy(self._prepare_for_class(lowerCamelCase,   lowerCamelCase))

               if not self.is_encoder_decoder:
                   _lowercase :							Optional[Any]   	=	inputs['input_ids']
                   del inputs["input_ids"]
               else:
                   _lowercase :							Tuple   	=	inputs['input_ids']
                   _lowercase :							Tuple   	=	inputs.get('decoder_input_ids',   lowerCamelCase)
                   del inputs["input_ids"]
                   inputs.pop('decoder_input_ids',   lowerCamelCase)

               _lowercase :							List[Any]   	=	model.get_input_embeddings()
               if not self.is_encoder_decoder:
                   _lowercase :							Union[str, Any]   	=	wte(lowerCamelCase)
               else:
                   _lowercase :							Dict   	=	wte(lowerCamelCase)
                   _lowercase :							Optional[Any]   	=	wte(lowerCamelCase)

               with torch.no_grad():
                   model(**lowerCamelCase)[0]




       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase	,       _lowercase :							Optional[int]   	=	self.model_tester.prepare_config_and_inputs()
           _lowercase :							Tuple   	=	input_dict['input_ids']
           _lowercase :							Optional[Any]   	=	input_ids.ne(1).to(lowerCamelCase)
           _lowercase :							Dict   	=	MaMaaaForConditionalGeneration(lowerCamelCase).eval().to(lowerCamelCase)
           if torch_device == "cuda":
               model.half()
           model.generate(lowerCamelCase,   attention_mask=lowerCamelCase)
           model.generate(num_beams=4,   do_sample=lowerCamelCase,   early_stopping=lowerCamelCase,   num_return_sequences=3)



def        UpperCamelCase_(   lowerCamelCase_				)					->		Union[str, Any]:
    return torch.tensor(lowerCamelCase_							,				dtype=torch.long							,				device=lowerCamelCase_				)


SCREAMING_SNAKE_CASE :   Union[str, Any]							      =				1E-4






@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class _lowerCamelCase(		unittest.TestCase     ):
       @cached_property
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M')
       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							List[Any]   	=	MaMaaaModel.from_pretrained('facebook/m2m100_418M').to(lowerCamelCase)
           _lowercase :							Optional[Any]   	=	_long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]])
           _lowercase :							Optional[int]   	=	_long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]])
           _lowercase :							str   	=	prepare_mam_aaa_inputs_dict(model.config,   lowerCamelCase,   lowerCamelCase)
           with torch.no_grad():
               _lowercase :							Tuple   	=	model(**lowerCamelCase)[0]
           _lowercase :							List[str]   	=	torch.Size((1, 11, 10_24))
           self.assertEqual(output.shape,   lowerCamelCase)
           # change to expected output here
           _lowercase :							Optional[int]   	=	torch.tensor(
               [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]],   device=lowerCamelCase)
           self.assertTrue(torch.allclose(output[:, :3, :3],   lowerCamelCase,   atol=lowerCamelCase))
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M').to(lowerCamelCase)

           # change to intended input
           _lowercase :							Optional[int]   	=	_long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]])
           _lowercase :							List[Any]   	=	_long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]])
           _lowercase :							int   	=	prepare_mam_aaa_inputs_dict(model.config,   lowerCamelCase,   lowerCamelCase)
           with torch.no_grad():
               _lowercase :							Tuple   	=	model(**lowerCamelCase)[0]
           _lowercase :							Any   	=	torch.Size((1, 11, model.config.vocab_size))
           self.assertEqual(output.shape,   lowerCamelCase)
           # change to expected output here
           _lowercase :							List[Any]   	=	torch.tensor(
               [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]],   device=lowerCamelCase)
           self.assertTrue(torch.allclose(output[:, :3, :3],   lowerCamelCase,   atol=lowerCamelCase))




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




           """simple docstring"""

           _lowercase :							int   	=	MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M').to(lowerCamelCase)
           _lowercase :							Optional[int]   	=	MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M',   src_lang='fr',   tgt_lang='en')

           _lowercase :							Tuple   	=	[
               'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
               'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
               'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
               ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
               ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
           ]

           # The below article tests that we don't add any hypotheses outside of the top n_beams
           _lowercase :							Tuple   	=	tokenizer(lowerCamelCase,   padding=lowerCamelCase,   return_tensors='pt')

           _lowercase :							Any   	=	model.generate(
               input_ids=dct['input_ids'].to(lowerCamelCase),   attention_mask=dct['attention_mask'].to(lowerCamelCase),   num_beams=5,   forced_bos_token_id=tokenizer.get_lang_id('en'),   )

           _lowercase :							List[str]   	=	[
               'The NSA case highlights the total absence of intelligence debate',
               'I think there are two levels of response from the French government.',
               'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
               ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
               ' communications in France.',
           ]

           _lowercase :							List[Any]   	=	tokenizer.batch_decode(
               hypotheses_batch.tolist(),   clean_up_tokenization_spaces=lowerCamelCase,   skip_special_tokens=lowerCamelCase)
           assert generated == expected_en






from jiwer import compute_measures

import datasets


SCREAMING_SNAKE_CASE :   Tuple							      =				"\\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"

SCREAMING_SNAKE_CASE :   Optional[Any]							      =				"\\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"

SCREAMING_SNAKE_CASE :   Any							      =				"\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 _lowerCamelCase(		datasets.Metric     ):
       def     UpperCamelCase  (      self) ->     Optional[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',
               ],   )




       def     UpperCamelCase  (      self,   lowerCamelCase=None,   lowerCamelCase=None,   lowerCamelCase=False) ->     Optional[Any]:




           """simple docstring"""

           if concatenate_texts:
               return compute_measures(lowerCamelCase,   lowerCamelCase)["wer"]
           else:
               _lowercase :							Dict   	=	0
               _lowercase :							Optional[int]   	=	0
               for prediction, reference in zip(lowerCamelCase,   lowerCamelCase):
                   _lowercase :							List[Any]   	=	compute_measures(lowerCamelCase,   lowerCamelCase)
                   incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                   total += measures["substitutions"] + measures["deletions"] + measures["hits"]
               return incorrect / total


