


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__	(      a	:   List[Any]	,  a	:   List[Any]	,  a	:   Optional[Any]	,  a	:   Tuple=None	,  a	:   int=None	,  a	:   Optional[Any]=None	,  a	:   str=None	,  a	:   Tuple=None	,  )    ->	Union[str, Any]:





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




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






									"""simple docstring"""






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




						def  _snake_case					(	self						:   Tuple						)      ->str:






									"""simple docstring"""






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

									a__ :Optional[int]						  =    self.get_config()
									a__ :Optional[Any]						  =    prepare_mam_aaa_inputs_dict(__A   ,     __A   ,     __A						)
									return config, inputs_dict




						def  _snake_case					(	self						:   Tuple						)      ->str:






									"""simple docstring"""






									return MaMaaaConfig(
									    vocab_size=self.vocab_size   ,     d_model=self.hidden_size   ,     encoder_layers=self.num_hidden_layers   ,     decoder_layers=self.num_hidden_layers   ,     encoder_attention_heads=self.num_attention_heads   ,     decoder_attention_heads=self.num_attention_heads   ,     encoder_ffn_dim=self.intermediate_size   ,     decoder_ffn_dim=self.intermediate_size   ,     dropout=self.hidden_dropout_prob   ,     attention_dropout=self.attention_probs_dropout_prob   ,     encoder_layerdrop=self.encoder_layerdrop   ,     decoder_layerdrop=self.decoder_layerdrop   ,     max_position_embeddings=self.max_position_embeddings   ,     eos_token_id=self.eos_token_id   ,     bos_token_id=self.bos_token_id   ,     pad_token_id=self.pad_token_id   ,     )




						def  _snake_case					(	self						:   int						)      ->List[str]:






									"""simple docstring"""






									a__  ,  a__ :List[Any]						  =    self.prepare_config_and_inputs()
									return config, inputs_dict




						def  _snake_case					(	self						:   List[Any]   ,     __A						:   int   ,     __A						:   List[str]						)      ->List[Any]:






									"""simple docstring"""






									a__ :Optional[int]						  =    MaMaaaModel(config=__A						).get_decoder().to(__A						).eval()
									a__ :Union[str, Any]						  =    inputs_dict["input_ids"]
									a__ :int						  =    inputs_dict["attention_mask"]
									a__ :int						  =    inputs_dict["head_mask"]

									# first forward pass
									a__ :int						  =    model(__A   ,     attention_mask=__A   ,     head_mask=__A   ,     use_cache=__A						)

									a__  ,  a__ :Dict						  =    outputs.to_tuple()

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

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

									a__ :Union[str, Any]						  =    model(__A   ,     attention_mask=__A						)["last_hidden_state"]
									a__ :int						  =    model(__A   ,     attention_mask=__A   ,     past_key_values=__A						)[
									    "last_hidden_state"
									]

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






									"""simple docstring"""






									a__ :int						  =    MaMaaaModel(config=__A						).to(__A						).eval()
									a__ :Dict						  =    model(**__A						)

									a__ :Any						  =    outputs.encoder_last_hidden_state
									a__ :int						  =    outputs.last_hidden_state

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

									a__ :Optional[int]						  =    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:
												a__ :Tuple						  =    model.get_decoder()
												decoder.save_pretrained(__A						)
												a__ :Tuple						  =    MaMaaaDecoder.from_pretrained(__A						).to(__A						)

									a__ :Optional[int]						  =    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):
						lowerCamelCase_         =     (
						    (
						        MaMaaaModel,
						        MaMaaaForConditionalGeneration,
						    )
						    if is_torch_available()
						    else ()
						)
						lowerCamelCase_         =     (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
						lowerCamelCase_         =     (
						    {
						        'conversational': MaMaaaForConditionalGeneration,
						        'feature-extraction': MaMaaaModel,
						        'summarization': MaMaaaForConditionalGeneration,
						        'text2text-generation': MaMaaaForConditionalGeneration,
						        'translation': MaMaaaForConditionalGeneration,
						    }
						    if is_torch_available()
						    else {}
						)
						lowerCamelCase_         =     True
						lowerCamelCase_         =     True
						lowerCamelCase_         =     False
						lowerCamelCase_         =     False




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






									"""simple docstring"""






									a__ :Union[str, Any]						  =    MaMaaaModelTester(self						)
									a__ :Optional[Any]						  =    ConfigTester(self   ,     config_class=__A						)




						def  _snake_case					(	self						:   Optional[int]						)      ->str:






									"""simple docstring"""






									self.config_tester.run_common_tests()




						def  _snake_case					(	self						:   Optional[int]						)      ->Optional[Any]:






									"""simple docstring"""






									a__  ,  a__ :Optional[Any]						  =    self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
												a__ :Any						  =    model_class(__A						)

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




						def  _snake_case					(	self						:   Optional[Any]						)      ->Any:






									"""simple docstring"""






									a__ :Tuple						  =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_decoder_model_past_large_inputs(*__A						)




						def  _snake_case					(	self						:   Optional[int]						)      ->Dict:






									"""simple docstring"""






									a__ :Dict						  =    self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_encoder_decoder_model_standalone(*__A						)




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






									"""simple docstring"""






									a__  ,  a__ :str						  =    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
												a__ :Any						  =    model_class(__A						)
												model.to(__A						)
												model.eval()

												a__ :List[Any]						  =    copy.deepcopy(self._prepare_for_class(__A   ,     __A						)						)

												if not self.is_encoder_decoder:
															a__ :int						  =    inputs["input_ids"]
															del inputs["input_ids"]
												else:
															a__ :Tuple						  =    inputs["input_ids"]
															a__ :Dict						  =    inputs.get("decoder_input_ids"   ,     __A						)
															del inputs["input_ids"]
															inputs.pop("decoder_input_ids"   ,     __A						)

												a__ :Tuple						  =    model.get_input_embeddings()
												if not self.is_encoder_decoder:
															a__ :Optional[Any]						  =    wte(__A						)
												else:
															a__ :str						  =    wte(__A						)
															a__ :Tuple						  =    wte(__A						)

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






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






									"""simple docstring"""






									a__  ,  a__ :List[str]						  =    self.model_tester.prepare_config_and_inputs()
									a__ :List[Any]						  =    input_dict["input_ids"]
									a__ :Optional[int]						  =    input_ids.ne(1						).to(__A						)
									a__ :Optional[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 				lowerCamelCase__	(      a	:   Optional[Any]				)    ->	int:





			"""simple docstring"""
			return torch.tensor(a	,  dtype=torch.long	,  device=a				)


snake_case__			 =						1e-4







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




						@cached_property
						def  _snake_case					(	self						:   Any						)      ->Union[str, Any]:






									"""simple docstring"""






									return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"						)




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






									"""simple docstring"""






									a__ :Optional[Any]						  =    MaMaaaModel.from_pretrained("facebook/m2m100_418M"						).to(__A						)
									a__ :List[Any]						  =    _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]						)
									a__ :Optional[int]						  =    _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]						)
									a__ :Optional[int]						  =    prepare_mam_aaa_inputs_dict(model.config   ,     __A   ,     __A						)
									with torch.no_grad():
												a__ :Union[str, Any]						  =    model(**__A						)[0]
									a__ :Union[str, Any]						  =    torch.Size((1, 11, 1024)						)
									self.assertEqual(output.shape   ,     __A						)
									# change to expected output here
									a__ :Any						  =    torch.tensor(
									    [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]]   ,     device=__A						)
									self.assertTrue(torch.allclose(output[:, :3, :3]   ,     __A   ,     atol=__A						)						)




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






									"""simple docstring"""






									a__ :Tuple						  =    MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"						).to(__A						)

									# change to intended input
									a__ :List[Any]						  =    _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]						)
									a__ :List[str]						  =    _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]						)
									a__ :str						  =    prepare_mam_aaa_inputs_dict(model.config   ,     __A   ,     __A						)
									with torch.no_grad():
												a__ :Tuple						  =    model(**__A						)[0]
									a__ :Optional[Any]						  =    torch.Size((1, 11, model.config.vocab_size)						)
									self.assertEqual(output.shape   ,     __A						)
									# change to expected output here
									a__ :str						  =    torch.tensor(
									    [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]]   ,     device=__A						)
									self.assertTrue(torch.allclose(output[:, :3, :3]   ,     __A   ,     atol=__A						)						)






						def  _snake_case					(	self						:   int						)      ->Optional[Any]:






									"""simple docstring"""






									a__ :Optional[int]						  =    MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"						).to(__A						)
									a__ :int						  =    MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"   ,     src_lang="fr"   ,     tgt_lang="en"						)

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

									# The below article tests that we don't add any hypotheses outside of the top n_beams
									a__ :int						  =    tokenizer(__A   ,     padding=__A   ,     return_tensors="pt"						)

									a__ :List[str]						  =    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"						)   ,     )

									a__ :Union[str, 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.",
									]

									a__ :Any						  =    tokenizer.batch_decode(
									    hypotheses_batch.tolist()   ,     clean_up_tokenization_spaces=__A   ,     skip_special_tokens=__A						)
									assert generated == expected_en






def 				lowerCamelCase__	(      a	:   int	,  a	:   int				)    ->	Any:





			"""simple docstring"""
			# "extended trapezoidal rule"
			# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
			a__ :Optional[int]						  =    (boundary[1] - boundary[0]) / steps
			a__ :str						  =    boundary[0]
			a__ :Optional[int]						  =    boundary[1]
			a__ :str						  =    make_points(a	,  a	,  a				)
			a__ :Any						  =    0.0
			y += (h / 2.0) * f(a				)
			for i in x_i:
						# print(i)
						y += h * f(a				)
			y += (h / 2.0) * f(a				)
			return y


def 				lowerCamelCase__	(      a	:   Any	,  a	:   str	,  a	:   Dict				)    ->	int:





			"""simple docstring"""
			a__ :Union[str, Any]						  =    a + h
			while x < (b - h):
						yield x
						a__ :str						  =    x + h


def 				lowerCamelCase__	(      a	:   Optional[int]				)    ->	List[Any]:  # enter your function here





			"""simple docstring"""
			a__ :Tuple						  =    (x - 0) * (x - 0)
			return y


def 				lowerCamelCase__	(      )    ->	List[str]:





			"""simple docstring"""
			a__ :Optional[Any]						  =    0.0  # Lower bound of integration
			a__ :Optional[Any]						  =    1.0  # Upper bound of integration
			a__ :List[str]						  =    1_0.0  # define number of steps or resolution
			a__ :int						  =    [a, b]  # define boundary of integration
			a__ :str						  =    method_a(a	,  a				)
			print(F'''y = {y}'''				)


if __name__ == "__main__":
		main()


