






import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


lowerCamelCase       :       Dict        =				'''\

'''

lowerCamelCase       :       Optional[Any]        =				'''
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
'''

lowerCamelCase       :       Optional[Any]        =				'''
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to \'cuda\' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        78.22
        >>> print(round(results["perplexities"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = datasets.load_dataset("wikitext",
        ...                                     "wikitext-2-raw-v1",
        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!=\'\']
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        60.35
        >>> print(round(results["perplexities"][0], 2))
        81.12
'''

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

					'''simple docstring'''

					def 					lowerCAmelCase (     self :		List[Any]							)	->     str:


												"""simple docstring"""

												return datasets.MetricInfo(
												    description=_DESCRIPTION						,   citation=_CITATION						,   inputs_description=_KWARGS_DESCRIPTION						,   features=datasets.Features(
												        {
												            """input_texts""": datasets.Value("""string"""							),
												        }							)						,   reference_urls=["""https://huggingface.co/docs/transformers/perplexity"""]						,   )



					def 					lowerCAmelCase (     self :		int						,   __a :		Tuple						,   __a :		Tuple						,   __a :		int = 16						,   __a :		bool = True						,   __a :		str=None							)	->     Dict:


												"""simple docstring"""

												if device is not None:
																			assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
																			if device == "gpu":
																										__lowercase					:							str			=   """cuda"""
												else:
																			__lowercase					:							Any			=   """cuda""" if torch.cuda.is_available() else """cpu"""

												__lowercase					:							Tuple			=   AutoModelForCausalLM.from_pretrained(__a							)
												__lowercase					:							Union[str, Any]			=   model.to(__a							)

												__lowercase					:							str			=   AutoTokenizer.from_pretrained(__a							)

												# if batch_size > 1 (which generally leads to padding being required), and
												# if there is not an already assigned pad_token, assign an existing
												# special token to also be the padding token
												if tokenizer.pad_token is None and batch_size > 1:
																			__lowercase					:							Any			=   list(tokenizer.special_tokens_map_extended.values()							)
																			# check that the model already has at least one special token defined
																			assert (
																			    len(__a							) > 0
																			), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
																			# assign one of the special tokens to also be the pad token
																			tokenizer.add_special_tokens({"""pad_token""": existing_special_tokens[0]}							)

												if add_start_token:
																			# leave room for <BOS> token to be added:
																			assert (
																			    tokenizer.bos_token is not None
																			), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
																			__lowercase					:							List[str]			=   model.config.max_length - 1
												else:
																			__lowercase					:							List[Any]			=   model.config.max_length

												__lowercase					:							List[Any]			=   tokenizer(
												    __a						,   add_special_tokens=__a						,   padding=__a						,   truncation=__a						,   max_length=__a						,   return_tensors="""pt"""						,   return_attention_mask=__a						,   ).to(__a							)

												__lowercase					:							str			=   encodings["""input_ids"""]
												__lowercase					:							int			=   encodings["""attention_mask"""]

												# check that each input is long enough:
												if add_start_token:
																			assert torch.all(torch.ge(attn_masks.sum(1							)						,   1							)							), "Each input text must be at least one token long."
												else:
																			assert torch.all(
																			    torch.ge(attn_masks.sum(1							)						,   2							)							), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

												__lowercase					:							Union[str, Any]			=   []
												__lowercase					:							str			=   CrossEntropyLoss(reduction="""none"""							)

												for start_index in logging.tqdm(range(0						,   len(__a							)						,   __a							)							):
																			__lowercase					:							List[Any]			=   min(start_index + batch_size						,   len(__a							)							)
																			__lowercase					:							Any			=   encoded_texts[start_index:end_index]
																			__lowercase					:							Optional[Any]			=   attn_masks[start_index:end_index]

																			if add_start_token:
																										__lowercase					:							Optional[Any]			=   torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0							)							).to(__a							)
																										__lowercase					:							Dict			=   torch.cat([bos_tokens_tensor, encoded_batch]						,   dim=1							)
																										__lowercase					:							Dict			=   torch.cat(
																										    [torch.ones(bos_tokens_tensor.size()						,   dtype=torch.intaa							).to(__a							), attn_mask]						,   dim=1							)

																			__lowercase					:							Optional[int]			=   encoded_batch

																			with torch.no_grad():
																										__lowercase					:							Optional[int]			=   model(__a						,   attention_mask=__a							).logits

																			__lowercase					:							Optional[int]			=   out_logits[..., :-1, :].contiguous()
																			__lowercase					:							List[str]			=   labels[..., 1:].contiguous()
																			__lowercase					:							Any			=   attn_mask[..., 1:].contiguous()

																			__lowercase					:							int			=   torch.expa(
																			    (loss_fct(shift_logits.transpose(1						,   2							)						,   __a							) * shift_attention_mask_batch).sum(1							)
																			    / shift_attention_mask_batch.sum(1							)							)

																			ppls += perplexity_batch.tolist()

												return {"perplexities": ppls, "mean_perplexity": np.mean(__a							)}







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 					snake_case_						(   lowerCAmelCase_				:  Dict				,				lowerCAmelCase_				:  Dict				,				lowerCAmelCase_				:  str				,				lowerCAmelCase_				:  List[Any]=None				,				lowerCAmelCase_				:  Any=None				,				lowerCAmelCase_				:  List[Any]=None				,				lowerCAmelCase_				:  Optional[Any]=None				,				lowerCAmelCase_				:  Tuple=None				,				):
							if attention_mask is None:
														__lowercase					:							Tuple			=   input_ids.ne(config.pad_token_id					)
							if decoder_attention_mask is None:
														__lowercase					:							Any			=   decoder_input_ids.ne(config.pad_token_id					)
							if head_mask is None:
														__lowercase					:							Any			=   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					:							List[Any]			=   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   :

					'''simple docstring'''

					def __init__(     self :		Union[str, Any]						,   __a :		str						,   __a :		Tuple=13						,   __a :		List[Any]=7						,   __a :		Any=True						,   __a :		List[str]=False						,   __a :		Optional[Any]=99						,   __a :		Tuple=16						,   __a :		int=2						,   __a :		Optional[Any]=4						,   __a :		int=4						,   __a :		Any="relu"						,   __a :		Optional[int]=0.1						,   __a :		List[str]=0.1						,   __a :		Dict=0.0						,   __a :		List[str]=0.0						,   __a :		Union[str, Any]=20						,   __a :		str=2						,   __a :		str=1						,   __a :		Optional[int]=0						,   )	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							Any			=   parent
												__lowercase					:							Tuple			=   batch_size
												__lowercase					:							Any			=   seq_length
												__lowercase					:							Tuple			=   is_training
												__lowercase					:							Optional[Any]			=   use_labels
												__lowercase					:							Dict			=   vocab_size
												__lowercase					:							Optional[Any]			=   hidden_size
												__lowercase					:							Dict			=   num_hidden_layers
												__lowercase					:							Dict			=   num_attention_heads
												__lowercase					:							Dict			=   intermediate_size
												__lowercase					:							Union[str, Any]			=   hidden_act
												__lowercase					:							Union[str, Any]			=   hidden_dropout_prob
												__lowercase					:							Tuple			=   attention_probs_dropout_prob
												__lowercase					:							Tuple			=   encoder_layerdrop
												__lowercase					:							List[str]			=   decoder_layerdrop
												__lowercase					:							Any			=   max_position_embeddings
												__lowercase					:							Any			=   eos_token_id
												__lowercase					:							Dict			=   pad_token_id
												__lowercase					:							List[str]			=   bos_token_id



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							Tuple			=   ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size							)
												__lowercase					:							str			=   self.eos_token_id  # Eos Token
												__lowercase					:							str			=   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					:							Tuple			=   input_ids.clamp(self.pad_token_id + 1							)
												__lowercase					:							Optional[int]			=   decoder_input_ids.clamp(self.pad_token_id + 1							)

												__lowercase					:							List[str]			=   self.get_config()
												__lowercase					:							str			=   prepare_mam_aaa_inputs_dict(__a						,   __a						,   __a							)
												return config, inputs_dict



					def 					lowerCAmelCase (     self :		str							)	->     Dict:


												"""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 					lowerCAmelCase (     self :		Dict							)	->     str:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							int			=   self.prepare_config_and_inputs()
												return config, inputs_dict



					def 					lowerCAmelCase (     self :		int						,   __a :		str						,   __a :		str							)	->     int:


												"""simple docstring"""

												__lowercase					:							Optional[Any]			=   MaMaaaModel(config=__a							).get_decoder().to(__a							).eval()
												__lowercase					:							List[str]			=   inputs_dict["""input_ids"""]
												__lowercase					:							Dict			=   inputs_dict["""attention_mask"""]
												__lowercase					:							List[Any]			=   inputs_dict["""head_mask"""]

												# first forward pass
												__lowercase					:							List[str]			=   model(__a						,   attention_mask=__a						,   head_mask=__a						,   use_cache=__a							)

												__lowercase	,	__lowercase					:							str			=   outputs.to_tuple()

												# create hypothetical multiple next token and extent to next_input_ids
												__lowercase					:							Union[str, Any]			=   ids_tensor((self.batch_size, 3)						,   config.vocab_size							)
												__lowercase					:							str			=   ids_tensor((self.batch_size, 3)						,   2							)

												# append to next input_ids and
												__lowercase					:							List[Any]			=   torch.cat([input_ids, next_tokens]						,   dim=-1							)
												__lowercase					:							Optional[Any]			=   torch.cat([attention_mask, next_attn_mask]						,   dim=-1							)

												__lowercase					:							Optional[int]			=   model(__a						,   attention_mask=__a							)["""last_hidden_state"""]
												__lowercase					:							Union[str, Any]			=   model(__a						,   attention_mask=__a						,   past_key_values=__a							)[
												    """last_hidden_state"""
												]

												# select random slice
												__lowercase					:							Optional[int]			=   ids_tensor((1,)						,   output_from_past.shape[-1]							).item()
												__lowercase					:							int			=   output_from_no_past[:, -3:, random_slice_idx].detach()
												__lowercase					:							Optional[Any]			=   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(__a						,   __a						,   atol=1E-2							)							)



					def 					lowerCAmelCase (     self :		List[str]						,   __a :		Tuple						,   __a :		List[str]							)	->     str:


												"""simple docstring"""

												__lowercase					:							Dict			=   MaMaaaModel(config=__a							).to(__a							).eval()
												__lowercase					:							Any			=   model(**__a							)

												__lowercase					:							str			=   outputs.encoder_last_hidden_state
												__lowercase					:							Optional[Any]			=   outputs.last_hidden_state

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase					:							str			=   model.get_encoder()
																			encoder.save_pretrained(__a							)
																			__lowercase					:							List[Any]			=   MaMaaaEncoder.from_pretrained(__a							).to(__a							)

												__lowercase					:							Tuple			=   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					:							Tuple			=   model.get_decoder()
																			decoder.save_pretrained(__a							)
																			__lowercase					:							Tuple			=   MaMaaaDecoder.from_pretrained(__a							).to(__a							)

												__lowercase					:							Tuple			=   decoder(
												    input_ids=inputs_dict["""decoder_input_ids"""]						,   attention_mask=inputs_dict["""decoder_attention_mask"""]						,   encoder_hidden_states=__a						,   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	):

					'''simple docstring'''

					_A  :	int     =					(
					    (
					        MaMaaaModel,
					        MaMaaaForConditionalGeneration,
					    )
					    if is_torch_available()
					    else ()
					)
					_A  :	int     =					(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
					_A  :	Union[str, Any]     =					(
					    {
					        '''conversational''': MaMaaaForConditionalGeneration,
					        '''feature-extraction''': MaMaaaModel,
					        '''summarization''': MaMaaaForConditionalGeneration,
					        '''text2text-generation''': MaMaaaForConditionalGeneration,
					        '''translation''': MaMaaaForConditionalGeneration,
					    }
					    if is_torch_available()
					    else {}
					)
					_A  :	Optional[int]     =					True
					_A  :	Union[str, Any]     =					True
					_A  :	Any     =					False
					_A  :	int     =					False



					def 					lowerCAmelCase (     self :		str						,   __a :		Union[str, Any]						,   __a :		Optional[int]						,   __a :		List[Any]						,   __a :		Tuple						,   __a :		Optional[int]							)	->     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 					lowerCAmelCase (     self :		Union[str, Any]							)	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							int			=   MaMaaaModelTester(self							)
												__lowercase					:							Union[str, Any]			=   ConfigTester(self						,   config_class=__a							)



					def 					lowerCAmelCase (     self :		Any							)	->     str:


												"""simple docstring"""

												self.config_tester.run_common_tests()



					def 					lowerCAmelCase (     self :		List[Any]							)	->     Any:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							Any			=   self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																			__lowercase					:							List[str]			=   model_class(__a							)

																			with tempfile.TemporaryDirectory() as tmpdirname:
																										model.save_pretrained(__a							)
																										__lowercase	,	__lowercase					:							str			=   model_class.from_pretrained(__a						,   output_loading_info=__a							)
																			self.assertEqual(info["""missing_keys"""]						,   []							)



					def 					lowerCAmelCase (     self :		int							)	->     List[Any]:


												"""simple docstring"""

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



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


												"""simple docstring"""

												__lowercase					:							Optional[int]			=   self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.check_encoder_decoder_model_standalone(*__a							)



					def 					lowerCAmelCase (     self :		int							)	->     Any:


												"""simple docstring"""

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

												for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																			__lowercase					:							Union[str, Any]			=   model_class(__a							)
																			model.to(__a							)
																			model.eval()

																			__lowercase					:							Any			=   copy.deepcopy(self._prepare_for_class(__a						,   __a							)							)

																			if not self.is_encoder_decoder:
																										__lowercase					:							int			=   inputs["""input_ids"""]
																										del inputs["input_ids"]
																			else:
																										__lowercase					:							Optional[int]			=   inputs["""input_ids"""]
																										__lowercase					:							Optional[Any]			=   inputs.get("""decoder_input_ids"""						,   __a							)
																										del inputs["input_ids"]
																										inputs.pop("""decoder_input_ids"""						,   __a							)

																			__lowercase					:							Union[str, Any]			=   model.get_input_embeddings()
																			if not self.is_encoder_decoder:
																										__lowercase					:							Dict			=   wte(__a							)
																			else:
																										__lowercase					:							str			=   wte(__a							)
																										__lowercase					:							Union[str, Any]			=   wte(__a							)

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



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							str			=   self.model_tester.prepare_config_and_inputs()
												__lowercase					:							List[str]			=   input_dict["""input_ids"""]
												__lowercase					:							Optional[int]			=   input_ids.ne(1							).to(__a							)
												__lowercase					:							List[Any]			=   MaMaaaForConditionalGeneration(__a							).eval().to(__a							)
												if torch_device == "cuda":
																			model.half()
												model.generate(__a						,   attention_mask=__a							)
												model.generate(num_beams=4						,   do_sample=__a						,   early_stopping=__a						,   num_return_sequences=3							)







def 					snake_case_						(   lowerCAmelCase_				:  Optional[Any]					):
							return torch.tensor(lowerCAmelCase_				,				dtype=torch.long				,				device=lowerCAmelCase_					)


lowerCamelCase       :       Dict        =				1E-4



@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 						lowerCAmelCase   (       unittest.TestCase	):

					'''simple docstring'''

					@cached_property
					def 					lowerCAmelCase (     self :		List[str]							)	->     Tuple:


												"""simple docstring"""

												return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""							)



					def 					lowerCAmelCase (     self :		Any							)	->     Tuple:


												"""simple docstring"""

												__lowercase					:							List[str]			=   MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""							).to(__a							)
												__lowercase					:							Union[str, Any]			=   _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]							)
												__lowercase					:							int			=   _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]							)
												__lowercase					:							int			=   prepare_mam_aaa_inputs_dict(model.config						,   __a						,   __a							)
												with torch.no_grad():
																			__lowercase					:							int			=   model(**__a							)[0]
												__lowercase					:							int			=   torch.Size((1, 11, 1024)							)
												self.assertEqual(output.shape						,   __a							)
												# change to expected output here
												__lowercase					:							Dict			=   torch.tensor(
												    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]						,   device=__a							)
												self.assertTrue(torch.allclose(output[:, :3, :3]						,   __a						,   atol=__a							)							)



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


												"""simple docstring"""

												__lowercase					:							Tuple			=   MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""							).to(__a							)

												# change to intended input
												__lowercase					:							Any			=   _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]							)
												__lowercase					:							Union[str, Any]			=   _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]							)
												__lowercase					:							Tuple			=   prepare_mam_aaa_inputs_dict(model.config						,   __a						,   __a							)
												with torch.no_grad():
																			__lowercase					:							Optional[Any]			=   model(**__a							)[0]
												__lowercase					:							Tuple			=   torch.Size((1, 11, model.config.vocab_size)							)
												self.assertEqual(output.shape						,   __a							)
												# change to expected output here
												__lowercase					:							Union[str, Any]			=   torch.tensor(
												    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]						,   device=__a							)
												self.assertTrue(torch.allclose(output[:, :3, :3]						,   __a						,   atol=__a							)							)



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     int:


												"""simple docstring"""

												__lowercase					:							List[str]			=   MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""							).to(__a							)
												__lowercase					:							Tuple			=   MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""						,   src_lang="""fr"""						,   tgt_lang="""en"""							)

												__lowercase					:							Dict			=   [
												    """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					:							Union[str, Any]			=   tokenizer(__a						,   padding=__a						,   return_tensors="""pt"""							)

												__lowercase					:							Dict			=   model.generate(
												    input_ids=dct["""input_ids"""].to(__a							)						,   attention_mask=dct["""attention_mask"""].to(__a							)						,   num_beams=5						,   forced_bos_token_id=tokenizer.get_lang_id("""en"""							)						,   )

												__lowercase					:							Any			=   [
												    """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					:							Dict			=   tokenizer.batch_decode(
												    hypotheses_batch.tolist()						,   clean_up_tokenization_spaces=__a						,   skip_special_tokens=__a							)
												assert generated == expected_en