



'''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 A__   (					UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  ):
						if attention_mask is None:
												_UpperCamelCase :		int			    =       input_ids.ne(config.pad_token_id							)
						if decoder_attention_mask is None:
												_UpperCamelCase :		Tuple			    =       decoder_input_ids.ne(config.pad_token_id							)
						if head_mask is None:
												_UpperCamelCase :		str			    =       torch.ones(config.encoder_layers  ,  config.encoder_attention_heads  ,  device=UpperCAmelCase_							)
						if decoder_head_mask is None:
												_UpperCamelCase :		Any			    =       torch.ones(config.decoder_layers  ,  config.decoder_attention_heads  ,  device=UpperCAmelCase_							)
						if cross_attn_head_mask is None:
												_UpperCamelCase :		Union[str, Any]			    =       torch.ones(config.decoder_layers  ,  config.decoder_attention_heads  ,  device=UpperCAmelCase_							)
						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 							lowercase__     :





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







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





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Tuple			    =       ids_tensor([self.batch_size, self.seq_length]			,self.vocab_size			)
							_UpperCamelCase :		Optional[Any]			    =       self.eos_token_id  # Eos Token
							_UpperCamelCase :		Dict			    =       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 :		Tuple			    =       input_ids.clamp(self.pad_token_id + 1			)
							_UpperCamelCase :		List[str]			    =       decoder_input_ids.clamp(self.pad_token_id + 1			)

							_UpperCamelCase :		int			    =       self.get_config()
							_UpperCamelCase :		Union[str, Any]			    =       prepare_mam_aaa_inputs_dict(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			)
							return config, inputs_dict





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''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 :    Dict			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		List[str]			    =       self.prepare_config_and_inputs()
							return config, inputs_dict





	def      UpperCamelCase_  (			self :    int			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       MaMaaaModel(config=lowerCamelCase__			).get_decoder().to(lowerCamelCase__			).eval()
							_UpperCamelCase :		Tuple			    =       inputs_dict['input_ids']
							_UpperCamelCase :		Tuple			    =       inputs_dict['attention_mask']
							_UpperCamelCase :		Optional[Any]			    =       inputs_dict['head_mask']

							# first forward pass
							_UpperCamelCase :		Any			    =       model(lowerCamelCase__			,attention_mask=lowerCamelCase__			,head_mask=lowerCamelCase__			,use_cache=lowerCamelCase__			)

							_UpperCamelCase    ,      _UpperCamelCase :		Tuple			    =       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 :		List[str]			    =       ids_tensor((self.batch_size, 3)			,2			)

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

							_UpperCamelCase :		int			    =       model(lowerCamelCase__			,attention_mask=lowerCamelCase__			)['last_hidden_state']
							_UpperCamelCase :		str			    =       model(lowerCamelCase__			,attention_mask=lowerCamelCase__			,past_key_values=lowerCamelCase__			)[
							    'last_hidden_state'
							]

							# select random slice
							_UpperCamelCase :		str			    =       ids_tensor((1,)			,output_from_past.shape[-1]			).item()
							_UpperCamelCase :		int			    =       output_from_no_past[:, -3:, random_slice_idx].detach()
							_UpperCamelCase :		Tuple			    =       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 :    Tuple			,lowerCamelCase__ :    List[Any]			,lowerCamelCase__ :    List[str]			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       MaMaaaModel(config=lowerCamelCase__			).to(lowerCamelCase__			).eval()
							_UpperCamelCase :		Tuple			    =       model(**lowerCamelCase__			)

							_UpperCamelCase :		Union[str, Any]			    =       outputs.encoder_last_hidden_state
							_UpperCamelCase :		Tuple			    =       outputs.last_hidden_state

							with tempfile.TemporaryDirectory() as tmpdirname:
													_UpperCamelCase :		List[str]			    =       model.get_encoder()
													encoder.save_pretrained(lowerCamelCase__			)
													_UpperCamelCase :		int			    =       MaMaaaEncoder.from_pretrained(lowerCamelCase__			).to(lowerCamelCase__			)

							_UpperCamelCase :		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:
													_UpperCamelCase :		Optional[int]			    =       model.get_decoder()
													decoder.save_pretrained(lowerCamelCase__			)
													_UpperCamelCase :		List[str]			    =       MaMaaaDecoder.from_pretrained(lowerCamelCase__			).to(lowerCamelCase__			)

							_UpperCamelCase :		List[str]			    =       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 							lowercase__     (							lowercase						, lowercase						, lowercase						, unittest.TestCase       ):
	lowercase__      =      (
	    (
	        MaMaaaModel,
	        MaMaaaForConditionalGeneration,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__      =      (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
	lowercase__      =      (
	    {
	        """conversational""": MaMaaaForConditionalGeneration,
	        """feature-extraction""": MaMaaaModel,
	        """summarization""": MaMaaaForConditionalGeneration,
	        """text2text-generation""": MaMaaaForConditionalGeneration,
	        """translation""": MaMaaaForConditionalGeneration,
	    }
	    if is_torch_available()
	    else {}
	)
	lowercase__      =      True
	lowercase__      =      True
	lowercase__      =      False
	lowercase__      =      False





	def      UpperCamelCase_  (			self :    List[Any]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    str			,lowerCamelCase__ :    List[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      UpperCamelCase_  (			self :    Tuple			):







							'''simple docstring'''
							_UpperCamelCase :		str			    =       MaMaaaModelTester(self			)
							_UpperCamelCase :		str			    =       ConfigTester(self			,config_class=lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							self.config_tester.run_common_tests()





	def      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		List[str]			    =       self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
													_UpperCamelCase :		int			    =       model_class(lowerCamelCase__			)

													with tempfile.TemporaryDirectory() as tmpdirname:
																			model.save_pretrained(lowerCamelCase__			)
																			_UpperCamelCase    ,      _UpperCamelCase :		Dict			    =       model_class.from_pretrained(lowerCamelCase__			,output_loading_info=lowerCamelCase__			)
													self.assertEqual(info['missing_keys']			,[]			)





	def      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       self.model_tester.prepare_config_and_inputs_for_common()
							self.model_tester.check_encoder_decoder_model_standalone(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		int			    =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
													_UpperCamelCase :		str			    =       model_class(lowerCamelCase__			)
													model.to(lowerCamelCase__			)
													model.eval()

													_UpperCamelCase :		List[Any]			    =       copy.deepcopy(self._prepare_for_class(lowerCamelCase__			,lowerCamelCase__			)			)

													if not self.is_encoder_decoder:
																			_UpperCamelCase :		Tuple			    =       inputs['input_ids']
																			del inputs["input_ids"]
													else:
																			_UpperCamelCase :		List[Any]			    =       inputs['input_ids']
																			_UpperCamelCase :		Tuple			    =       inputs.get('decoder_input_ids'			,lowerCamelCase__			)
																			del inputs["input_ids"]
																			inputs.pop('decoder_input_ids'			,lowerCamelCase__			)

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

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





	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							_UpperCamelCase    ,      _UpperCamelCase :		Optional[Any]			    =       self.model_tester.prepare_config_and_inputs()
							_UpperCamelCase :		Union[str, Any]			    =       input_dict['input_ids']
							_UpperCamelCase :		int			    =       input_ids.ne(1			).to(lowerCamelCase__			)
							_UpperCamelCase :		Optional[int]			    =       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 A__   (					UpperCAmelCase_							):
						return torch.tensor(UpperCAmelCase_  ,  dtype=torch.long  ,  device=UpperCAmelCase_							)


snake_case_			:     Union[str, Any]  	=  1e-4






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





	@cached_property
	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       MaMaaaModel.from_pretrained('facebook/m2m100_418M'			).to(lowerCamelCase__			)
							_UpperCamelCase :		List[Any]			    =       _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]			)
							_UpperCamelCase :		Any			    =       _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]			)
							_UpperCamelCase :		str			    =       prepare_mam_aaa_inputs_dict(model.config			,lowerCamelCase__			,lowerCamelCase__			)
							with torch.no_grad():
													_UpperCamelCase :		Any			    =       model(**lowerCamelCase__			)[0]
							_UpperCamelCase :		List[str]			    =       torch.Size((1, 11, 1024)			)
							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      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'			).to(lowerCamelCase__			)

							# change to intended input
							_UpperCamelCase :		Optional[int]			    =       _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]			)
							_UpperCamelCase :		List[Any]			    =       _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]			)
							_UpperCamelCase :		Optional[Any]			    =       prepare_mam_aaa_inputs_dict(model.config			,lowerCamelCase__			,lowerCamelCase__			)
							with torch.no_grad():
													_UpperCamelCase :		int			    =       model(**lowerCamelCase__			)[0]
							_UpperCamelCase :		List[Any]			    =       torch.Size((1, 11, model.config.vocab_size)			)
							self.assertEqual(output.shape			,lowerCamelCase__			)
							# change to expected output here
							_UpperCamelCase :		Optional[int]			    =       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 :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'			).to(lowerCamelCase__			)
							_UpperCamelCase :		Optional[int]			    =       MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'			,src_lang='fr'			,tgt_lang='en'			)

							_UpperCamelCase :		Optional[Any]			    =       [
							    '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 :		List[str]			    =       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 :		Tuple			    =       [
							    '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 :		int			    =       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 A__   (					UpperCAmelCase_							):
						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}'							)


