



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    lowerCamelCase_(lowerCamelCase_    ,   lowerCamelCase_    ,   lowerCamelCase_    ,   lowerCamelCase_=None    ,   lowerCamelCase_=None    ,   lowerCamelCase_=None    ,   lowerCamelCase_=None    ,   lowerCamelCase_=None    ,   ) ->       Optional[Any]:
						if attention_mask is None:
												UpperCAmelCase         =     input_ids.ne(config.pad_token_id    )
						if decoder_attention_mask is None:
												UpperCAmelCase         =     decoder_input_ids.ne(config.pad_token_id    )
						if head_mask is None:
												UpperCAmelCase         =     torch.ones(config.encoder_layers    ,   config.encoder_attention_heads    ,   device=lowerCamelCase_    )
						if decoder_head_mask is None:
												UpperCAmelCase         =     torch.ones(config.decoder_layers    ,   config.decoder_attention_heads    ,   device=lowerCamelCase_    )
						if cross_attn_head_mask is None:
												UpperCAmelCase         =     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  __magic_name__   :






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







								UpperCAmelCase         =     parent
								UpperCAmelCase         =     batch_size
								UpperCAmelCase         =     seq_length
								UpperCAmelCase         =     is_training
								UpperCAmelCase         =     use_labels
								UpperCAmelCase         =     vocab_size
								UpperCAmelCase         =     hidden_size
								UpperCAmelCase         =     num_hidden_layers
								UpperCAmelCase         =     num_attention_heads
								UpperCAmelCase         =     intermediate_size
								UpperCAmelCase         =     hidden_act
								UpperCAmelCase         =     hidden_dropout_prob
								UpperCAmelCase         =     attention_probs_dropout_prob
								UpperCAmelCase         =     encoder_layerdrop
								UpperCAmelCase         =     decoder_layerdrop
								UpperCAmelCase         =     max_position_embeddings
								UpperCAmelCase         =     eos_token_id
								UpperCAmelCase         =     pad_token_id
								UpperCAmelCase         =     bos_token_id






		def SCREAMING_SNAKE_CASE_			(						self      :     str      )				->					Union[str, Any]:
								'''simple docstring'''







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

								UpperCAmelCase         =     self.get_config()
								UpperCAmelCase         =     prepare_mam_aaa_inputs_dict(UpperCamelCase__				,		UpperCamelCase__				,		UpperCamelCase__      )
								return config, inputs_dict






		def SCREAMING_SNAKE_CASE_			(						self      :     Any      )				->					Optional[int]:
								'''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 SCREAMING_SNAKE_CASE_			(						self      :     List[Any]      )				->					Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase       ,		UpperCAmelCase         =     self.prepare_config_and_inputs()
								return config, inputs_dict






		def SCREAMING_SNAKE_CASE_			(						self      :     int				,		UpperCamelCase__      :     str				,		UpperCamelCase__      :     Union[str, Any]      )				->					Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase         =     MaMaaaModel(config=UpperCamelCase__      ).get_decoder().to(UpperCamelCase__      ).eval()
								UpperCAmelCase         =     inputs_dict["input_ids"]
								UpperCAmelCase         =     inputs_dict["attention_mask"]
								UpperCAmelCase         =     inputs_dict["head_mask"]

								# first forward pass
								UpperCAmelCase         =     model(UpperCamelCase__				,		attention_mask=UpperCamelCase__				,		head_mask=UpperCamelCase__				,		use_cache=UpperCamelCase__      )

								UpperCAmelCase       ,		UpperCAmelCase         =     outputs.to_tuple()

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

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

								UpperCAmelCase         =     model(UpperCamelCase__				,		attention_mask=UpperCamelCase__      )["last_hidden_state"]
								UpperCAmelCase         =     model(UpperCamelCase__				,		attention_mask=UpperCamelCase__				,		past_key_values=UpperCamelCase__      )[
								    "last_hidden_state"
								]

								# select random slice
								UpperCAmelCase         =     ids_tensor((1,)				,		output_from_past.shape[-1]      ).item()
								UpperCAmelCase         =     output_from_no_past[:, -3:, random_slice_idx].detach()
								UpperCAmelCase         =     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(UpperCamelCase__				,		UpperCamelCase__				,		atol=1e-2      )      )







		def SCREAMING_SNAKE_CASE_			(						self      :     List[Any]				,		UpperCamelCase__      :     Optional[int]				,		UpperCamelCase__      :     Optional[Any]      )				->					Optional[int]:
								'''simple docstring'''







								UpperCAmelCase         =     MaMaaaModel(config=UpperCamelCase__      ).to(UpperCamelCase__      ).eval()
								UpperCAmelCase         =     model(**UpperCamelCase__      )

								UpperCAmelCase         =     outputs.encoder_last_hidden_state
								UpperCAmelCase         =     outputs.last_hidden_state

								with tempfile.TemporaryDirectory() as tmpdirname:
														UpperCAmelCase         =     model.get_encoder()
														encoder.save_pretrained(UpperCamelCase__      )
														UpperCAmelCase         =     MaMaaaEncoder.from_pretrained(UpperCamelCase__      ).to(UpperCamelCase__      )

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

								UpperCAmelCase         =     decoder(
								    input_ids=inputs_dict["decoder_input_ids"]				,		attention_mask=inputs_dict["decoder_attention_mask"]				,		encoder_hidden_states=UpperCamelCase__				,		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  __magic_name__   (							A__,  A__,  A__,  unittest.TestCase						):
		lowercase      :       Union[str, Any]          =(
		    (
		        MaMaaaModel,
		        MaMaaaForConditionalGeneration,
		    )
		    if is_torch_available()
		    else ()
		)
		lowercase      :       List[str]          =(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
		lowercase      :       Tuple          =(
		    {
		        '''conversational''': MaMaaaForConditionalGeneration,
		        '''feature-extraction''': MaMaaaModel,
		        '''summarization''': MaMaaaForConditionalGeneration,
		        '''text2text-generation''': MaMaaaForConditionalGeneration,
		        '''translation''': MaMaaaForConditionalGeneration,
		    }
		    if is_torch_available()
		    else {}
		)
		lowercase      :       str          =True
		lowercase      :       Tuple          =True
		lowercase      :       List[str]          =False
		lowercase      :       Tuple          =False






		def SCREAMING_SNAKE_CASE_			(						self      :     Tuple				,		UpperCamelCase__      :     List[str]				,		UpperCamelCase__      :     Optional[int]				,		UpperCamelCase__      :     Optional[Any]				,		UpperCamelCase__      :     Dict				,		UpperCamelCase__      :     Dict      )				->					str:
								'''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 SCREAMING_SNAKE_CASE_			(						self      :     int      )				->					Any:
								'''simple docstring'''







								UpperCAmelCase         =     MaMaaaModelTester(self      )
								UpperCAmelCase         =     ConfigTester(self				,		config_class=UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     int      )				->					Dict:
								'''simple docstring'''







								self.config_tester.run_common_tests()






		def SCREAMING_SNAKE_CASE_			(						self      :     Union[str, Any]      )				->					List[Any]:
								'''simple docstring'''







								UpperCAmelCase       ,		UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs()
								for model_class in self.all_model_classes:
														UpperCAmelCase         =     model_class(UpperCamelCase__      )

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






		def SCREAMING_SNAKE_CASE_			(						self      :     Union[str, Any]      )				->					Optional[int]:
								'''simple docstring'''







								UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     int      )				->					Tuple:
								'''simple docstring'''







								UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.check_encoder_decoder_model_standalone(*UpperCamelCase__      )






		def SCREAMING_SNAKE_CASE_			(						self      :     str      )				->					str:
								'''simple docstring'''







								UpperCAmelCase       ,		UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
														UpperCAmelCase         =     model_class(UpperCamelCase__      )
														model.to(UpperCamelCase__      )
														model.eval()

														UpperCAmelCase         =     copy.deepcopy(self._prepare_for_class(UpperCamelCase__				,		UpperCamelCase__      )      )

														if not self.is_encoder_decoder:
																				UpperCAmelCase         =     inputs["input_ids"]
																				del inputs["input_ids"]
														else:
																				UpperCAmelCase         =     inputs["input_ids"]
																				UpperCAmelCase         =     inputs.get("decoder_input_ids"				,		UpperCamelCase__      )
																				del inputs["input_ids"]
																				inputs.pop("decoder_input_ids"				,		UpperCamelCase__      )

														UpperCAmelCase         =     model.get_input_embeddings()
														if not self.is_encoder_decoder:
																				UpperCAmelCase         =     wte(UpperCamelCase__      )
														else:
																				UpperCAmelCase         =     wte(UpperCamelCase__      )
																				UpperCAmelCase         =     wte(UpperCamelCase__      )

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







		def SCREAMING_SNAKE_CASE_			(						self      :     Dict      )				->					Optional[Any]:
								'''simple docstring'''







								UpperCAmelCase       ,		UpperCAmelCase         =     self.model_tester.prepare_config_and_inputs()
								UpperCAmelCase         =     input_dict["input_ids"]
								UpperCAmelCase         =     input_ids.ne(1      ).to(UpperCamelCase__      )
								UpperCAmelCase         =     MaMaaaForConditionalGeneration(UpperCamelCase__      ).eval().to(UpperCamelCase__      )
								if torch_device == "cuda":
														model.half()
								model.generate(UpperCamelCase__				,		attention_mask=UpperCamelCase__      )
								model.generate(num_beams=4				,		do_sample=UpperCamelCase__				,		early_stopping=UpperCamelCase__				,		num_return_sequences=3      )

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


__lowerCamelCase     :							List[str]  							=				1E-4





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






		@cached_property
		def SCREAMING_SNAKE_CASE_			(						self      :     List[str]      )				->					Optional[Any]:
								'''simple docstring'''







								return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"      )






		def SCREAMING_SNAKE_CASE_			(						self      :     List[str]      )				->					List[str]:
								'''simple docstring'''







								UpperCAmelCase         =     MaMaaaModel.from_pretrained("facebook/m2m100_418M"      ).to(UpperCamelCase__      )
								UpperCAmelCase         =     _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]      )
								UpperCAmelCase         =     _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]      )
								UpperCAmelCase         =     prepare_mam_aaa_inputs_dict(model.config				,		UpperCamelCase__				,		UpperCamelCase__      )
								with torch.no_grad():
														UpperCAmelCase         =     model(**UpperCamelCase__      )[0]
								UpperCAmelCase         =     torch.Size((1, 11, 10_24)      )
								self.assertEqual(output.shape				,		UpperCamelCase__      )
								# change to expected output here
								UpperCAmelCase         =     torch.tensor(
								    [[-0.77_80, -0.16_76, 0.10_38], [-6.75_56, -1.39_92, 0.05_67], [-7.53_83, -0.59_20, -0.27_79]]				,		device=UpperCamelCase__      )
								self.assertTrue(torch.allclose(output[:, :3, :3]				,		UpperCamelCase__				,		atol=UpperCamelCase__      )      )






		def SCREAMING_SNAKE_CASE_			(						self      :     Any      )				->					str:
								'''simple docstring'''







								UpperCAmelCase         =     MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"      ).to(UpperCamelCase__      )

								# change to intended input
								UpperCAmelCase         =     _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]      )
								UpperCAmelCase         =     _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]      )
								UpperCAmelCase         =     prepare_mam_aaa_inputs_dict(model.config				,		UpperCamelCase__				,		UpperCamelCase__      )
								with torch.no_grad():
														UpperCAmelCase         =     model(**UpperCamelCase__      )[0]
								UpperCAmelCase         =     torch.Size((1, 11, model.config.vocab_size)      )
								self.assertEqual(output.shape				,		UpperCamelCase__      )
								# change to expected output here
								UpperCAmelCase         =     torch.tensor(
								    [[-1.04_48, -1.04_11, 3.79_92], [-3.21_91, -3.23_86, -1.34_51], [-3.62_10, -3.59_93, 0.49_25]]				,		device=UpperCamelCase__      )
								self.assertTrue(torch.allclose(output[:, :3, :3]				,		UpperCamelCase__				,		atol=UpperCamelCase__      )      )







		def SCREAMING_SNAKE_CASE_			(						self      :     List[Any]      )				->					Union[str, Any]:
								'''simple docstring'''







								UpperCAmelCase         =     MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"      ).to(UpperCamelCase__      )
								UpperCAmelCase         =     MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"				,		src_lang="fr"				,		tgt_lang="en"      )

								UpperCAmelCase         =     [
								    "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
								UpperCAmelCase         =     tokenizer(UpperCamelCase__				,		padding=UpperCamelCase__				,		return_tensors="pt"      )

								UpperCAmelCase         =     model.generate(
								    input_ids=dct["input_ids"].to(UpperCamelCase__      )				,		attention_mask=dct["attention_mask"].to(UpperCamelCase__      )				,		num_beams=5				,		forced_bos_token_id=tokenizer.get_lang_id("en"      )				,		)

								UpperCAmelCase         =     [
								    "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.",
								]

								UpperCAmelCase         =     tokenizer.batch_decode(
								    hypotheses_batch.tolist()				,		clean_up_tokenization_spaces=UpperCamelCase__				,		skip_special_tokens=UpperCamelCase__      )
								assert generated == expected_en








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


__lowerCamelCase     :							Any  							=				{
    "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__lowerCamelCase     :							Optional[int]  							=				[
		    "MEGA_PRETRAINED_MODEL_ARCHIVE_LIST",
		    "MegaForCausalLM",
		    "MegaForMaskedLM",
		    "MegaForMultipleChoice",
		    "MegaForQuestionAnswering",
		    "MegaForSequenceClassification",
		    "MegaForTokenClassification",
		    "MegaModel",
		    "MegaPreTrainedModel",
		]

if TYPE_CHECKING:
		from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_mega import (
				    MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
				    MegaForCausalLM,
				    MegaForMaskedLM,
				    MegaForMultipleChoice,
				    MegaForQuestionAnswering,
				    MegaForSequenceClassification,
				    MegaForTokenClassification,
				    MegaModel,
				    MegaPreTrainedModel,
				)

else:
		import sys

		__lowerCamelCase     :							int  							=				_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



