






"""simple docstring"""
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      (   A__	,A__	,A__	,A__=None	,A__=None	,A__=None	,A__=None	,A__=None	,):
			if attention_mask is None:
						UpperCAmelCase_     : str			     =					input_ids.ne(config.pad_token_id						)
			if decoder_attention_mask is None:
						UpperCAmelCase_     : Dict			     =					decoder_input_ids.ne(config.pad_token_id						)
			if head_mask is None:
						UpperCAmelCase_     : Optional[Any]			     =					torch.ones(config.encoder_layers	,config.encoder_attention_heads	,device=A__						)
			if decoder_head_mask is None:
						UpperCAmelCase_     : List[Any]			     =					torch.ones(config.decoder_layers	,config.decoder_attention_heads	,device=A__						)
			if cross_attn_head_mask is None:
						UpperCAmelCase_     : Optional[Any]			     =					torch.ones(config.decoder_layers	,config.decoder_attention_heads	,device=A__						)
			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 			UpperCamelCase_       :





	def __init__(      self					: Optional[Any]	,	lowerCAmelCase_					: Any	,	lowerCAmelCase_					: Any=13	,	lowerCAmelCase_					: str=7	,	lowerCAmelCase_					: Dict=True	,	lowerCAmelCase_					: Optional[int]=False	,	lowerCAmelCase_					: Tuple=99	,	lowerCAmelCase_					: str=16	,	lowerCAmelCase_					: Optional[int]=2	,	lowerCAmelCase_					: Any=4	,	lowerCAmelCase_					: Tuple=4	,	lowerCAmelCase_					: Union[str, Any]="relu"	,	lowerCAmelCase_					: Optional[Any]=0.1	,	lowerCAmelCase_					: List[Any]=0.1	,	lowerCAmelCase_					: List[Any]=0.0	,	lowerCAmelCase_					: List[str]=0.0	,	lowerCAmelCase_					: str=20	,	lowerCAmelCase_					: Tuple=2	,	lowerCAmelCase_					: Tuple=1	,	lowerCAmelCase_					: List[Any]=0	,	)						->			Dict:
				UpperCAmelCase_     : List[str]			     =					parent
				UpperCAmelCase_     : int			     =					batch_size
				UpperCAmelCase_     : Optional[Any]			     =					seq_length
				UpperCAmelCase_     : Any			     =					is_training
				UpperCAmelCase_     : List[str]			     =					use_labels
				UpperCAmelCase_     : Optional[int]			     =					vocab_size
				UpperCAmelCase_     : Any			     =					hidden_size
				UpperCAmelCase_     : str			     =					num_hidden_layers
				UpperCAmelCase_     : Optional[int]			     =					num_attention_heads
				UpperCAmelCase_     : Any			     =					intermediate_size
				UpperCAmelCase_     : Any			     =					hidden_act
				UpperCAmelCase_     : Any			     =					hidden_dropout_prob
				UpperCAmelCase_     : Optional[int]			     =					attention_probs_dropout_prob
				UpperCAmelCase_     : List[str]			     =					encoder_layerdrop
				UpperCAmelCase_     : List[Any]			     =					decoder_layerdrop
				UpperCAmelCase_     : Dict			     =					max_position_embeddings
				UpperCAmelCase_     : List[Any]			     =					eos_token_id
				UpperCAmelCase_     : str			     =					pad_token_id
				UpperCAmelCase_     : int			     =					bos_token_id





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

				UpperCAmelCase_     : Tuple			     =					self.get_config()
				UpperCAmelCase_     : List[Any]			     =					prepare_mam_aaa_inputs_dict(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_						)
				return config, inputs_dict





	def      _SCREAMING_SNAKE_CASE      (      self					: int						)						->			int:
				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					: str						)						->			List[Any]:
				UpperCAmelCase_     ,	UpperCAmelCase_     : List[Any]			     =					self.prepare_config_and_inputs()
				return config, inputs_dict





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]	,	lowerCAmelCase_					: Optional[Any]	,	lowerCAmelCase_					: List[Any]						)						->			int:
				UpperCAmelCase_     : Optional[Any]			     =					MaMaaaModel(config=lowerCAmelCase_						).get_decoder().to(lowerCAmelCase_						).eval()
				UpperCAmelCase_     : str			     =					inputs_dict["input_ids"]
				UpperCAmelCase_     : Optional[int]			     =					inputs_dict["attention_mask"]
				UpperCAmelCase_     : Union[str, Any]			     =					inputs_dict["head_mask"]

				# first forward pass
				UpperCAmelCase_     : Optional[int]			     =					model(lowerCAmelCase_	,	attention_mask=lowerCAmelCase_	,	head_mask=lowerCAmelCase_	,	use_cache=lowerCAmelCase_						)

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

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

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

				UpperCAmelCase_     : List[str]			     =					model(lowerCAmelCase_	,	attention_mask=lowerCAmelCase_						)["last_hidden_state"]
				UpperCAmelCase_     : Any			     =					model(lowerCAmelCase_	,	attention_mask=lowerCAmelCase_	,	past_key_values=lowerCAmelCase_						)[
				    "last_hidden_state"
				]

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





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]	,	lowerCAmelCase_					: Tuple	,	lowerCAmelCase_					: List[str]						)						->			str:
				UpperCAmelCase_     : str			     =					MaMaaaModel(config=lowerCAmelCase_						).to(lowerCAmelCase_						).eval()
				UpperCAmelCase_     : int			     =					model(**lowerCAmelCase_						)

				UpperCAmelCase_     : Dict			     =					outputs.encoder_last_hidden_state
				UpperCAmelCase_     : Union[str, Any]			     =					outputs.last_hidden_state

				with tempfile.TemporaryDirectory() as tmpdirname:
							UpperCAmelCase_     : Union[str, Any]			     =					model.get_encoder()
							encoder.save_pretrained(lowerCAmelCase_						)
							UpperCAmelCase_     : List[str]			     =					MaMaaaEncoder.from_pretrained(lowerCAmelCase_						).to(lowerCAmelCase_						)

				UpperCAmelCase_     : List[str]			     =					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_     : Dict			     =					model.get_decoder()
							decoder.save_pretrained(lowerCAmelCase_						)
							UpperCAmelCase_     : Dict			     =					MaMaaaDecoder.from_pretrained(lowerCAmelCase_						).to(lowerCAmelCase_						)

				UpperCAmelCase_     : Dict			     =					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 			UpperCamelCase_       (__A				,						__A				,						__A				,						unittest.TestCase     ):
	__magic_name__	      =				(
	    (
	        MaMaaaModel,
	        MaMaaaForConditionalGeneration,
	    )
	    if is_torch_available()
	    else ()
	)
	__magic_name__	      =				(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
	__magic_name__	      =				(
	    {
	        '''conversational''': MaMaaaForConditionalGeneration,
	        '''feature-extraction''': MaMaaaModel,
	        '''summarization''': MaMaaaForConditionalGeneration,
	        '''text2text-generation''': MaMaaaForConditionalGeneration,
	        '''translation''': MaMaaaForConditionalGeneration,
	    }
	    if is_torch_available()
	    else {}
	)
	__magic_name__	      =				True
	__magic_name__	      =				True
	__magic_name__	      =				False
	__magic_name__	      =				False





	def      _SCREAMING_SNAKE_CASE      (      self					: Dict	,	lowerCAmelCase_					: Union[str, Any]	,	lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: Any	,	lowerCAmelCase_					: str	,	lowerCAmelCase_					: Optional[int]						)						->			str:
				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					: Union[str, Any]						)						->			Tuple:
				UpperCAmelCase_     : List[str]			     =					MaMaaaModelTester(self						)
				UpperCAmelCase_     : Dict			     =					ConfigTester(self	,	config_class=lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			int:
				self.config_tester.run_common_tests()





	def      _SCREAMING_SNAKE_CASE      (      self					: Any						)						->			Union[str, Any]:
				UpperCAmelCase_     ,	UpperCAmelCase_     : Any			     =					self.model_tester.prepare_config_and_inputs()
				for model_class in self.all_model_classes:
							UpperCAmelCase_     : List[str]			     =					model_class(lowerCAmelCase_						)

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





	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple						)						->			str:
				UpperCAmelCase_     : Optional[int]			     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]						)						->			Union[str, Any]:
				UpperCAmelCase_     : Optional[int]			     =					self.model_tester.prepare_config_and_inputs_for_common()
				self.model_tester.check_encoder_decoder_model_standalone(*lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]						)						->			Dict:
				UpperCAmelCase_     ,	UpperCAmelCase_     : Union[str, Any]			     =					self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
							UpperCAmelCase_     : Dict			     =					model_class(lowerCAmelCase_						)
							model.to(lowerCAmelCase_						)
							model.eval()

							UpperCAmelCase_     : Optional[Any]			     =					copy.deepcopy(self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_						)						)

							if not self.is_encoder_decoder:
										UpperCAmelCase_     : Optional[int]			     =					inputs["input_ids"]
										del inputs["input_ids"]
							else:
										UpperCAmelCase_     : Dict			     =					inputs["input_ids"]
										UpperCAmelCase_     : Dict			     =					inputs.get("decoder_input_ids"	,	lowerCAmelCase_						)
										del inputs["input_ids"]
										inputs.pop("decoder_input_ids"	,	lowerCAmelCase_						)

							UpperCAmelCase_     : Optional[int]			     =					model.get_input_embeddings()
							if not self.is_encoder_decoder:
										UpperCAmelCase_     : str			     =					wte(lowerCAmelCase_						)
							else:
										UpperCAmelCase_     : Optional[int]			     =					wte(lowerCAmelCase_						)
										UpperCAmelCase_     : Dict			     =					wte(lowerCAmelCase_						)

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





	def      _SCREAMING_SNAKE_CASE      (      self					: int						)						->			Optional[int]:
				UpperCAmelCase_     ,	UpperCAmelCase_     : int			     =					self.model_tester.prepare_config_and_inputs()
				UpperCAmelCase_     : List[str]			     =					input_dict["input_ids"]
				UpperCAmelCase_     : Optional[Any]			     =					input_ids.ne(1						).to(lowerCAmelCase_						)
				UpperCAmelCase_     : Optional[Any]			     =					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 				snake_case      (   A__						):
			return torch.tensor(A__	,dtype=torch.long	,device=A__						)


lowerCamelCase_					=      1E-4







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





	@cached_property
	def      _SCREAMING_SNAKE_CASE      (      self					: Dict						)						->			Dict:
				return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]						)						->			Optional[int]:
				UpperCAmelCase_     : Union[str, Any]			     =					MaMaaaModel.from_pretrained("facebook/m2m100_418M"						).to(lowerCAmelCase_						)
				UpperCAmelCase_     : Optional[Any]			     =					_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]						)
				UpperCAmelCase_     : Optional[int]			     =					_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]						)
				UpperCAmelCase_     : str			     =					prepare_mam_aaa_inputs_dict(model.config	,	lowerCAmelCase_	,	lowerCAmelCase_						)
				with torch.no_grad():
							UpperCAmelCase_     : List[str]			     =					model(**lowerCAmelCase_						)[0]
				UpperCAmelCase_     : int			     =					torch.Size((1, 11, 1_024)						)
				self.assertEqual(output.shape	,	lowerCAmelCase_						)
				# change to expected output here
				UpperCAmelCase_     : 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      _SCREAMING_SNAKE_CASE      (      self					: List[Any]						)						->			Any:
				UpperCAmelCase_     : str			     =					MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"						).to(lowerCAmelCase_						)

				# change to intended input
				UpperCAmelCase_     : int			     =					_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]						)
				UpperCAmelCase_     : Union[str, Any]			     =					_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]						)
				UpperCAmelCase_     : Optional[Any]			     =					prepare_mam_aaa_inputs_dict(model.config	,	lowerCAmelCase_	,	lowerCAmelCase_						)
				with torch.no_grad():
							UpperCAmelCase_     : Tuple			     =					model(**lowerCAmelCase_						)[0]
				UpperCAmelCase_     : Union[str, Any]			     =					torch.Size((1, 11, model.config.vocab_size)						)
				self.assertEqual(output.shape	,	lowerCAmelCase_						)
				# change to expected output here
				UpperCAmelCase_     : Union[str, 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      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			Optional[int]:
				UpperCAmelCase_     : Optional[int]			     =					MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"						).to(lowerCAmelCase_						)
				UpperCAmelCase_     : Tuple			     =					MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"	,	src_lang="fr"	,	tgt_lang="en"						)

				UpperCAmelCase_     : str			     =					[
				    "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_     : int			     =					tokenizer(lowerCAmelCase_	,	padding=lowerCAmelCase_	,	return_tensors="pt"						)

				UpperCAmelCase_     : List[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"						)	,	)

				UpperCAmelCase_     : 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.",
				]

				UpperCAmelCase_     : List[str]			     =					tokenizer.batch_decode(
				    hypotheses_batch.tolist()	,	clean_up_tokenization_spaces=lowerCAmelCase_	,	skip_special_tokens=lowerCAmelCase_						)
				assert generated == expected_en











"""simple docstring"""
from torch import nn

def 				snake_case      (   A__						):
			if act_fn in ["swish", "silu"]:
						return nn.SiLU()
			elif act_fn == "mish":
						return nn.Mish()
			elif act_fn == "gelu":
						return nn.GELU()
			else:
						raise ValueError(F"""Unsupported activation function: {act_fn}"""						)



