



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  UpperCAmelCase__    (    lowercase__						,       lowercase__						,       lowercase__						,       lowercase__=None						,       lowercase__=None						,       lowercase__=None						,       lowercase__=None						,       lowercase__=None						,       ) ->      Optional[Any]:
						if attention_mask is None:
												__lowercase					=				input_ids.ne(config.pad_token_id   )
						if decoder_attention_mask is None:
												__lowercase					=				decoder_input_ids.ne(config.pad_token_id   )
						if head_mask is None:
												__lowercase					=				torch.ones(config.encoder_layers						,       config.encoder_attention_heads						,       device=lowercase__   )
						if decoder_head_mask is None:
												__lowercase					=				torch.ones(config.decoder_layers						,       config.decoder_attention_heads						,       device=lowercase__   )
						if cross_attn_head_mask is None:
												__lowercase					=				torch.ones(config.decoder_layers						,       config.decoder_attention_heads						,       device=lowercase__   )
						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]			,     lowercase	:       Optional[Any]			,     lowercase	:       Any=13			,     lowercase	:       Union[str, Any]=7			,     lowercase	:       Any=True			,     lowercase	:       List[Any]=False			,     lowercase	:       List[str]=99			,     lowercase	:       List[Any]=16			,     lowercase	:       int=2			,     lowercase	:       str=4			,     lowercase	:       List[Any]=4			,     lowercase	:       int="relu"			,     lowercase	:       Dict=0.1			,     lowercase	:       str=0.1			,     lowercase	:       List[Any]=0.0			,     lowercase	:       Optional[int]=0.0			,     lowercase	:       Tuple=20			,     lowercase	:       str=2			,     lowercase	:       Dict=1			,     lowercase	:       List[Any]=0			,     )						->					Tuple:
									"""simple docstring"""







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





			def 		snake_case__			(				self	:       Optional[int]   )						->					str:
									"""simple docstring"""







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

									__lowercase					=				self.get_config()
									__lowercase					=				prepare_mam_aaa_inputs_dict(lowercase			,     lowercase			,     lowercase   )
									return config, inputs_dict





			def 		snake_case__			(				self	:       Tuple   )						->					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 		snake_case__			(				self	:       str   )						->					Dict:
									"""simple docstring"""







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





			def 		snake_case__			(				self	:       int			,     lowercase	:       Optional[int]			,     lowercase	:       Any   )						->					List[Any]:
									"""simple docstring"""







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

									# first forward pass
									__lowercase					=				model(lowercase			,     attention_mask=lowercase			,     head_mask=lowercase			,     use_cache=lowercase   )

									__lowercase	,			__lowercase					=				outputs.to_tuple()

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

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

									__lowercase					=				model(lowercase			,     attention_mask=lowercase   )["""last_hidden_state"""]
									__lowercase					=				model(lowercase			,     attention_mask=lowercase			,     past_key_values=lowercase   )[
									    """last_hidden_state"""
									]

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







			def 		snake_case__			(				self	:       Tuple			,     lowercase	:       Optional[Any]			,     lowercase	:       Dict   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				MaMaaaModel(config=lowercase   ).to(lowercase   ).eval()
									__lowercase					=				model(**lowercase   )

									__lowercase					=				outputs.encoder_last_hidden_state
									__lowercase					=				outputs.last_hidden_state

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

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

									__lowercase					=				decoder(
									    input_ids=inputs_dict["""decoder_input_ids"""]			,     attention_mask=inputs_dict["""decoder_attention_mask"""]			,     encoder_hidden_states=lowercase			,     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   ( _UpperCAmelCase    ,					_UpperCAmelCase    ,					_UpperCAmelCase    ,					unittest.TestCase			):






			"""simple docstring"""





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





			def 		snake_case__			(				self	:       Tuple			,     lowercase	:       List[str]			,     lowercase	:       Any			,     lowercase	:       Any			,     lowercase	:       Dict			,     lowercase	:       Tuple   )						->					Optional[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	:       Any   )						->					Any:
									"""simple docstring"""







									__lowercase					=				MaMaaaModelTester(self   )
									__lowercase					=				ConfigTester(self			,     config_class=lowercase   )





			def 		snake_case__			(				self	:       Optional[Any]   )						->					Dict:
									"""simple docstring"""







									self.config_tester.run_common_tests()





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







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
															__lowercase					=				model_class(lowercase   )

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





			def 		snake_case__			(				self	:       Tuple   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowercase   )





			def 		snake_case__			(				self	:       Optional[Any]   )						->					str:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_encoder_decoder_model_standalone(*lowercase   )





			def 		snake_case__			(				self	:       Any   )						->					List[str]:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
															__lowercase					=				model_class(lowercase   )
															model.to(lowercase   )
															model.eval()

															__lowercase					=				copy.deepcopy(self._prepare_for_class(lowercase			,     lowercase   )   )

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

															__lowercase					=				model.get_input_embeddings()
															if not self.is_encoder_decoder:
																					__lowercase					=				wte(lowercase   )
															else:
																					__lowercase					=				wte(lowercase   )
																					__lowercase					=				wte(lowercase   )

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







			def 		snake_case__			(				self	:       Optional[Any]   )						->					Any:
									"""simple docstring"""







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






def  UpperCAmelCase__    (    lowercase__   ) ->      Dict:
						return torch.tensor(lowercase__						,       dtype=torch.long						,       device=lowercase__   )


UpperCamelCase__ =						1e-4







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






			"""simple docstring"""





			@cached_property
			def 		snake_case__			(				self	:       int   )						->					Optional[Any]:
									"""simple docstring"""







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





			def 		snake_case__			(				self	:       List[str]   )						->					str:
									"""simple docstring"""







									__lowercase					=				MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""   ).to(lowercase   )
									__lowercase					=				_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]   )
									__lowercase					=				_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]   )
									__lowercase					=				prepare_mam_aaa_inputs_dict(model.config			,     lowercase			,     lowercase   )
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )[0]
									__lowercase					=				torch.Size((1, 11, 1_024)   )
									self.assertEqual(output.shape			,     lowercase   )
									# change to expected output here
									__lowercase					=				torch.tensor(
									    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]			,     device=lowercase   )
									self.assertTrue(torch.allclose(output[:, :3, :3]			,     lowercase			,     atol=lowercase   )   )





			def 		snake_case__			(				self	:       Tuple   )						->					str:
									"""simple docstring"""







									__lowercase					=				MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""   ).to(lowercase   )

									# change to intended input
									__lowercase					=				_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]   )
									__lowercase					=				_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]   )
									__lowercase					=				prepare_mam_aaa_inputs_dict(model.config			,     lowercase			,     lowercase   )
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )[0]
									__lowercase					=				torch.Size((1, 11, model.config.vocab_size)   )
									self.assertEqual(output.shape			,     lowercase   )
									# change to expected output here
									__lowercase					=				torch.tensor(
									    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]			,     device=lowercase   )
									self.assertTrue(torch.allclose(output[:, :3, :3]			,     lowercase			,     atol=lowercase   )   )







			def 		snake_case__			(				self	:       Any   )						->					List[str]:
									"""simple docstring"""







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

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

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

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










def  UpperCAmelCase__    (    lowercase__						,       lowercase__   ) ->      bool:
						__lowercase					=				len(lowercase__   )
						__lowercase					=				[[False] * (required_sum + 1) for _ in range(arr_len + 1   )]

						# for each arr value, a sum of zero(0) can be formed by not taking any element
						# hence True/1
						for i in range(arr_len + 1   ):
												__lowercase					=				True

						# sum is not zero and set is empty then false
						for i in range(1						,       required_sum + 1   ):
												__lowercase					=				False

						for i in range(1						,       arr_len + 1   ):
												for j in range(1						,       required_sum + 1   ):
																		if arr[i - 1] > j:
																								__lowercase					=				subset[i - 1][j]
																		if arr[i - 1] <= j:
																								__lowercase					=				subset[i - 1][j] or subset[i - 1][j - arr[i - 1]]

						return subset[arr_len][required_sum]


if __name__ == "__main__":
			import doctest

			doctest.testmod()





