




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    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					):
				if attention_mask is None:
								_lowerCamelCase  :    Optional[Any]					=					input_ids.ne(config.pad_token_id	)
				if decoder_attention_mask is None:
								_lowerCamelCase  :    str					=					decoder_input_ids.ne(config.pad_token_id	)
				if head_mask is None:
								_lowerCamelCase  :    Optional[Any]					=					torch.ones(config.encoder_layers							,					config.encoder_attention_heads							,					device=lowercase__	)
				if decoder_head_mask is None:
								_lowerCamelCase  :    List[str]					=					torch.ones(config.decoder_layers							,					config.decoder_attention_heads							,					device=lowercase__	)
				if cross_attn_head_mask is None:
								_lowerCamelCase  :    int					=					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						,   lowercase						,   lowercase=13						,   lowercase=7						,   lowercase=True						,   lowercase=False						,   lowercase=99						,   lowercase=16						,   lowercase=2						,   lowercase=4						,   lowercase=4						,   lowercase="relu"						,   lowercase=0.1						,   lowercase=0.1						,   lowercase=0.0						,   lowercase=0.0						,   lowercase=20						,   lowercase=2						,   lowercase=1						,   lowercase=0						,   ):
							_lowerCamelCase  :    List[Any]					=					parent
							_lowerCamelCase  :    Tuple					=					batch_size
							_lowerCamelCase  :    List[str]					=					seq_length
							_lowerCamelCase  :    List[Any]					=					is_training
							_lowerCamelCase  :    Optional[Any]					=					use_labels
							_lowerCamelCase  :    Optional[Any]					=					vocab_size
							_lowerCamelCase  :    Optional[Any]					=					hidden_size
							_lowerCamelCase  :    str					=					num_hidden_layers
							_lowerCamelCase  :    Optional[Any]					=					num_attention_heads
							_lowerCamelCase  :    str					=					intermediate_size
							_lowerCamelCase  :    Dict					=					hidden_act
							_lowerCamelCase  :    List[str]					=					hidden_dropout_prob
							_lowerCamelCase  :    str					=					attention_probs_dropout_prob
							_lowerCamelCase  :    Dict					=					encoder_layerdrop
							_lowerCamelCase  :    List[str]					=					decoder_layerdrop
							_lowerCamelCase  :    int					=					max_position_embeddings
							_lowerCamelCase  :    str					=					eos_token_id
							_lowerCamelCase  :    Tuple					=					pad_token_id
							_lowerCamelCase  :    List[str]					=					bos_token_id
			def       A_					(						self						):
							_lowerCamelCase  :    Union[str, Any]					=					ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size						)
							_lowerCamelCase  :    Dict					=					self.eos_token_id  # Eos Token
							_lowerCamelCase  :    Union[str, Any]					=					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
							_lowerCamelCase  :    List[str]					=					input_ids.clamp(self.pad_token_id + 1						)
							_lowerCamelCase  :    List[str]					=					decoder_input_ids.clamp(self.pad_token_id + 1						)

							_lowerCamelCase  :    Optional[Any]					=					self.get_config()
							_lowerCamelCase  :    Union[str, Any]					=					prepare_mam_aaa_inputs_dict(lowercase						,   lowercase						,   lowercase						)
							return config, inputs_dict
			def       A_					(						self						):
							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       A_					(						self						):
							_lowerCamelCase  :    List[Any]					=					self.prepare_config_and_inputs()
							return config, inputs_dict
			def       A_					(						self						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    Any					=					MaMaaaModel(config=lowercase						).get_decoder().to(lowercase						).eval()
							_lowerCamelCase  :    int					=					inputs_dict['input_ids']
							_lowerCamelCase  :    Union[str, Any]					=					inputs_dict['attention_mask']
							_lowerCamelCase  :    List[str]					=					inputs_dict['head_mask']

							# first forward pass
							_lowerCamelCase  :    List[Any]					=					model(lowercase						,   attention_mask=lowercase						,   head_mask=lowercase						,   use_cache=lowercase						)

							_lowerCamelCase  :    Any					=					outputs.to_tuple()

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

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

							_lowerCamelCase  :    Optional[Any]					=					model(lowercase						,   attention_mask=lowercase						)['last_hidden_state']
							_lowerCamelCase  :    str					=					model(lowercase						,   attention_mask=lowercase						,   past_key_values=lowercase						)[
							    'last_hidden_state'
							]

							# select random slice
							_lowerCamelCase  :    Any					=					ids_tensor((1,)						,   output_from_past.shape[-1]						).item()
							_lowerCamelCase  :    int					=					output_from_no_past[:, -3:, random_slice_idx].detach()
							_lowerCamelCase  :    str					=					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       A_					(						self						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    List[str]					=					MaMaaaModel(config=lowercase						).to(lowercase						).eval()
							_lowerCamelCase  :    Optional[Any]					=					model(**lowercase						)

							_lowerCamelCase  :    List[str]					=					outputs.encoder_last_hidden_state
							_lowerCamelCase  :    Optional[int]					=					outputs.last_hidden_state

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

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

							_lowerCamelCase  :    int					=					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__			(  lowercase,			lowercase,			lowercase,			unittest.TestCase		):






			'''simple docstring'''



			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       A_					(						self						,   lowercase						,   lowercase						,   lowercase						,   lowercase						,   lowercase						):
							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       A_					(						self						):
							_lowerCamelCase  :    int					=					MaMaaaModelTester(self						)
							_lowerCamelCase  :    str					=					ConfigTester(self						,   config_class=lowercase						)
			def       A_					(						self						):
							self.config_tester.run_common_tests()
			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
											_lowerCamelCase  :    Any					=					model_class(lowercase						)

											with tempfile.TemporaryDirectory() as tmpdirname:
															model.save_pretrained(lowercase						)
															_lowerCamelCase  :    Any					=					model_class.from_pretrained(lowercase						,   output_loading_info=lowercase						)
											self.assertEqual(info['missing_keys']						,   []						)
			def       A_					(						self						):
							_lowerCamelCase  :    List[str]					=					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowercase						)
			def       A_					(						self						):
							_lowerCamelCase  :    str					=					self.model_tester.prepare_config_and_inputs_for_common()
							self.model_tester.check_encoder_decoder_model_standalone(*lowercase						)
			def       A_					(						self						):
							_lowerCamelCase  :    str					=					self.model_tester.prepare_config_and_inputs_for_common()

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

											_lowerCamelCase  :    Optional[Any]					=					copy.deepcopy(self._prepare_for_class(lowercase						,   lowercase						)						)

											if not self.is_encoder_decoder:
															_lowerCamelCase  :    List[Any]					=					inputs['input_ids']
															del inputs["input_ids"]
											else:
															_lowerCamelCase  :    Union[str, Any]					=					inputs['input_ids']
															_lowerCamelCase  :    Optional[int]					=					inputs.get('decoder_input_ids'						,   lowercase						)
															del inputs["input_ids"]
															inputs.pop('decoder_input_ids'						,   lowercase						)

											_lowerCamelCase  :    List[str]					=					model.get_input_embeddings()
											if not self.is_encoder_decoder:
															_lowerCamelCase  :    Any					=					wte(lowercase						)
											else:
															_lowerCamelCase  :    Any					=					wte(lowercase						)
															_lowerCamelCase  :    str					=					wte(lowercase						)

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






			def       A_					(						self						):
							_lowerCamelCase  :    str					=					self.model_tester.prepare_config_and_inputs()
							_lowerCamelCase  :    Dict					=					input_dict['input_ids']
							_lowerCamelCase  :    List[str]					=					input_ids.ne(1						).to(lowercase						)
							_lowerCamelCase  :    Optional[int]					=					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   _snake_case    (       lowercase__	):
				return torch.tensor(lowercase__							,					dtype=torch.long							,					device=lowercase__	)


lowercase__  		=		1E-4






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






			'''simple docstring'''



			@cached_property
			def       A_					(						self						):
							return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'						)
			def       A_					(						self						):
							_lowerCamelCase  :    Dict					=					MaMaaaModel.from_pretrained('facebook/m2m100_418M'						).to(lowercase						)
							_lowerCamelCase  :    Tuple					=					_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]						)
							_lowerCamelCase  :    Dict					=					_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]						)
							_lowerCamelCase  :    Dict					=					prepare_mam_aaa_inputs_dict(model.config						,   lowercase						,   lowercase						)
							with torch.no_grad():
											_lowerCamelCase  :    int					=					model(**lowercase						)[0]
							_lowerCamelCase  :    Optional[Any]					=					torch.Size((1, 11, 1024)						)
							self.assertEqual(output.shape						,   lowercase						)
							# change to expected output here
							_lowerCamelCase  :    int					=					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=lowercase						)
							self.assertTrue(torch.allclose(output[:, :3, :3]						,   lowercase						,   atol=lowercase						)						)
			def       A_					(						self						):
							_lowerCamelCase  :    int					=					MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'						).to(lowercase						)

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






			def       A_					(						self						):
							_lowerCamelCase  :    Optional[int]					=					MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'						).to(lowercase						)
							_lowerCamelCase  :    Any					=					MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'						,   src_lang='fr'						,   tgt_lang='en'						)

							_lowerCamelCase  :    int					=					[
							    '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
							_lowerCamelCase  :    int					=					tokenizer(lowercase						,   padding=lowercase						,   return_tensors='pt'						)

							_lowerCamelCase  :    Optional[int]					=					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'						)						,   )

							_lowerCamelCase  :    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.',
							]

							_lowerCamelCase  :    Union[str, Any]					=					tokenizer.batch_decode(
							    hypotheses_batch.tolist()						,   clean_up_tokenization_spaces=lowercase						,   skip_special_tokens=lowercase						)
							assert generated == expected_en





"""simple docstring"""






from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


lowercase__  		=		logging.get_logger(__name__)

lowercase__  		=		{
    """google/umt5-small""": """https://huggingface.co/google/umt5-small/resolve/main/config.json""",
    # See all umt5 models at https://huggingface.co/models?filter=umt5
}






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    """umt5"""
			lowerCamelCase__   =    ["""past_key_values"""]
			def __init__(						self						,   lowercase=250112						,   lowercase=512						,   lowercase=64						,   lowercase=1024						,   lowercase=8						,   lowercase=None						,   lowercase=6						,   lowercase=32						,   lowercase=128						,   lowercase=0.1						,   lowercase=1E-6						,   lowercase=1.0						,   lowercase="gated-gelu"						,   lowercase=True						,   lowercase=True						,   lowercase="T5Tokenizer"						,   lowercase=True						,   lowercase=0						,   lowercase=1						,   lowercase=0						,   **lowercase						,   ):
							super().__init__(
							    is_encoder_decoder=lowercase						,   tokenizer_class=lowercase						,   tie_word_embeddings=lowercase						,   pad_token_id=lowercase						,   eos_token_id=lowercase						,   decoder_start_token_id=lowercase						,   **lowercase						,   )
							_lowerCamelCase  :    Union[str, Any]					=					vocab_size
							_lowerCamelCase  :    Optional[Any]					=					d_model
							_lowerCamelCase  :    Optional[Any]					=					d_kv
							_lowerCamelCase  :    Optional[int]					=					d_ff
							_lowerCamelCase  :    List[str]					=					num_layers
							_lowerCamelCase  :    Union[str, Any]					=					(
							    num_decoder_layers if num_decoder_layers is not None else self.num_layers
							)  # default = symmetry
							_lowerCamelCase  :    List[str]					=					num_heads
							_lowerCamelCase  :    int					=					relative_attention_num_buckets
							_lowerCamelCase  :    Union[str, Any]					=					relative_attention_max_distance
							_lowerCamelCase  :    int					=					dropout_rate
							_lowerCamelCase  :    List[Any]					=					layer_norm_epsilon
							_lowerCamelCase  :    Union[str, Any]					=					initializer_factor
							_lowerCamelCase  :    List[Any]					=					feed_forward_proj
							_lowerCamelCase  :    Dict					=					use_cache

							_lowerCamelCase  :    Dict					=					self.feed_forward_proj.split('-'						)
							_lowerCamelCase  :    List[str]					=					act_info[-1]
							_lowerCamelCase  :    int					=					act_info[0] == 'gated'

							if len(lowercase						) > 1 and act_info[0] != "gated" or len(lowercase						) > 2:
											raise ValueError(
											    F'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
											    'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
											    '\'gated-gelu\' or \'relu\''						)

							if feed_forward_proj == "gated-gelu":
											_lowerCamelCase  :    Optional[int]					=					'gelu_new'
			@property
			def       A_					(						self						):
							return self.d_model
			@property
			def       A_					(						self						):
							return self.num_heads






			@property
			def       A_					(						self						):
							return self.num_layers






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			@property
			# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					{
							    'input_ids': {0: 'batch', 1: 'encoder_sequence'},
							    'attention_mask': {0: 'batch', 1: 'encoder_sequence'},
							}
							if self.use_past:
											_lowerCamelCase  :    Optional[int]					=					'past_encoder_sequence + sequence'
											_lowerCamelCase  :    int					=					{0: 'batch'}
											_lowerCamelCase  :    List[str]					=					{0: 'batch', 1: 'past_decoder_sequence + sequence'}
							else:
											_lowerCamelCase  :    Dict					=					{0: 'batch', 1: 'decoder_sequence'}
											_lowerCamelCase  :    str					=					{0: 'batch', 1: 'decoder_sequence'}

							if self.use_past:
											self.fill_with_past_key_values_(lowercase						,   direction='inputs'						)

							return common_inputs
			@property
			# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
			def       A_					(						self						):
							return 13






			@property
			def       A_					(						self						):
							return 5E-4