




'''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_							(      __snake_case							:			Optional[int]   ,       __snake_case							:			Optional[Any]   ,       __snake_case							:			str   ,       __snake_case							:			Optional[int]=None   ,       __snake_case							:			List[str]=None   ,       __snake_case							:			Optional[Any]=None   ,       __snake_case							:			Optional[int]=None   ,       __snake_case							:			List[str]=None   ,       )							->						int:



       """simple docstring"""
       if attention_mask is None:
              lowerCamelCase_							=input_ids.ne(config.pad_token_id   )
       if decoder_attention_mask is None:
              lowerCamelCase_							=decoder_input_ids.ne(config.pad_token_id   )
       if head_mask is None:
              lowerCamelCase_							=torch.ones(config.encoder_layers   ,       config.encoder_attention_heads   ,       device=__snake_case   )
       if decoder_head_mask is None:
              lowerCamelCase_							=torch.ones(config.decoder_layers   ,       config.decoder_attention_heads   ,       device=__snake_case   )
       if cross_attn_head_mask is None:
              lowerCamelCase_							=torch.ones(config.decoder_layers   ,       config.decoder_attention_heads   ,       device=__snake_case   )
       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,		lowerCAmelCase,		lowerCAmelCase=13,		lowerCAmelCase=7,		lowerCAmelCase=True,		lowerCAmelCase=False,		lowerCAmelCase=99,		lowerCAmelCase=16,		lowerCAmelCase=2,		lowerCAmelCase=4,		lowerCAmelCase=4,		lowerCAmelCase="relu",		lowerCAmelCase=0.1,		lowerCAmelCase=0.1,		lowerCAmelCase=0.0,		lowerCAmelCase=0.0,		lowerCAmelCase=20,		lowerCAmelCase=2,		lowerCAmelCase=1,		lowerCAmelCase=0,		):



              """simple docstring"""







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






       def      lowercase__     (							self  ):



              """simple docstring"""







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

              lowerCamelCase_							=self.get_config()
              lowerCamelCase_							=prepare_mam_aaa_inputs_dict(lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  )
              return config, inputs_dict






       def      lowercase__     (							self  ):



              """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      lowercase__     (							self  ):



              """simple docstring"""







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






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=MaMaaaModel(config=lowerCAmelCase  ).get_decoder().to(lowerCAmelCase  ).eval()
              lowerCamelCase_							=inputs_dict['''input_ids''']
              lowerCamelCase_							=inputs_dict['''attention_mask''']
              lowerCamelCase_							=inputs_dict['''head_mask''']

              # first forward pass
              lowerCamelCase_							=model(lowerCAmelCase,		attention_mask=lowerCAmelCase,		head_mask=lowerCAmelCase,		use_cache=lowerCAmelCase  )

              lowerCamelCase_,      lowerCamelCase_							=outputs.to_tuple()

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

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

              lowerCamelCase_							=model(lowerCAmelCase,		attention_mask=lowerCAmelCase  )['''last_hidden_state''']
              lowerCamelCase_							=model(lowerCAmelCase,		attention_mask=lowerCAmelCase,		past_key_values=lowerCAmelCase  )[
                  '''last_hidden_state'''
              ]

              # select random slice
              lowerCamelCase_							=ids_tensor((1,),		output_from_past.shape[-1]  ).item()
              lowerCamelCase_							=output_from_no_past[:, -3:, random_slice_idx].detach()
              lowerCamelCase_							=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      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=MaMaaaModel(config=lowerCAmelCase  ).to(lowerCAmelCase  ).eval()
              lowerCamelCase_							=model(**lowerCAmelCase  )

              lowerCamelCase_							=outputs.encoder_last_hidden_state
              lowerCamelCase_							=outputs.last_hidden_state

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

              lowerCamelCase_							=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_							=model.get_decoder()
                     decoder.save_pretrained(lowerCAmelCase  )
                     lowerCamelCase_							=MaMaaaDecoder.from_pretrained(lowerCAmelCase  ).to(lowerCAmelCase  )

              lowerCamelCase_							=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       ( lowerCamelCase__			,					lowerCamelCase__			,					lowerCamelCase__			,					unittest.TestCase				):
       lowercase	:    Union[str, Any]      						=(
           (
               MaMaaaModel,
               MaMaaaForConditionalGeneration,
           )
           if is_torch_available()
           else ()
       )
       lowercase	:    Dict      						=(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
       lowercase	:    Optional[int]      						=(
           {
               'conversational': MaMaaaForConditionalGeneration,
               'feature-extraction': MaMaaaModel,
               'summarization': MaMaaaForConditionalGeneration,
               'text2text-generation': MaMaaaForConditionalGeneration,
               'translation': MaMaaaForConditionalGeneration,
           }
           if is_torch_available()
           else {}
       )
       lowercase	:    Dict      						=True
       lowercase	:    Tuple      						=True
       lowercase	:    Optional[Any]      						=False
       lowercase	:    int      						=False






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  ):



              """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      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=MaMaaaModelTester(self  )
              lowerCamelCase_							=ConfigTester(self,		config_class=lowerCAmelCase  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              self.config_tester.run_common_tests()






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_,      lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              for model_class in self.all_model_classes:
                     lowerCamelCase_							=model_class(lowerCAmelCase  )

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






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCAmelCase  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()
              self.model_tester.check_encoder_decoder_model_standalone(*lowerCAmelCase  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_,      lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                     lowerCamelCase_							=model_class(lowerCAmelCase  )
                     model.to(lowerCAmelCase  )
                     model.eval()

                     lowerCamelCase_							=copy.deepcopy(self._prepare_for_class(lowerCAmelCase,		lowerCAmelCase  )  )

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

                     lowerCamelCase_							=model.get_input_embeddings()
                     if not self.is_encoder_decoder:
                            lowerCamelCase_							=wte(lowerCAmelCase  )
                     else:
                            lowerCamelCase_							=wte(lowerCAmelCase  )
                            lowerCamelCase_							=wte(lowerCAmelCase  )

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






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_,      lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              lowerCamelCase_							=input_dict['''input_ids''']
              lowerCamelCase_							=input_ids.ne(1  ).to(lowerCAmelCase  )
              lowerCamelCase_							=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_							(      __snake_case							:			Tuple   )							->						List[Any]:



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


a_      :		int							      =       1e-4


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






       @cached_property
       def      lowercase__     (							self  ):



              """simple docstring"""







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






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=MaMaaaModel.from_pretrained('''facebook/m2m100_418M'''  ).to(lowerCAmelCase  )
              lowerCamelCase_							=_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]  )
              lowerCamelCase_							=_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]  )
              lowerCamelCase_							=prepare_mam_aaa_inputs_dict(model.config,		lowerCAmelCase,		lowerCAmelCase  )
              with torch.no_grad():
                     lowerCamelCase_							=model(**lowerCAmelCase  )[0]
              lowerCamelCase_							=torch.Size((1, 11, 1_024)  )
              self.assertEqual(output.shape,		lowerCAmelCase  )
              # change to expected output here
              lowerCamelCase_							=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      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''  ).to(lowerCAmelCase  )

              # change to intended input
              lowerCamelCase_							=_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]  )
              lowerCamelCase_							=_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]  )
              lowerCamelCase_							=prepare_mam_aaa_inputs_dict(model.config,		lowerCAmelCase,		lowerCAmelCase  )
              with torch.no_grad():
                     lowerCamelCase_							=model(**lowerCAmelCase  )[0]
              lowerCamelCase_							=torch.Size((1, 11, model.config.vocab_size)  )
              self.assertEqual(output.shape,		lowerCAmelCase  )
              # change to expected output here
              lowerCamelCase_							=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      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M'''  ).to(lowerCAmelCase  )
              lowerCamelCase_							=MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M''',		src_lang='''fr''',		tgt_lang='''en'''  )

              lowerCamelCase_							=[
                  '''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_							=tokenizer(lowerCAmelCase,		padding=lowerCAmelCase,		return_tensors='''pt'''  )

              lowerCamelCase_							=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'''  ),		)

              lowerCamelCase_							=[
                  '''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_							=tokenizer.batch_decode(
                  hypotheses_batch.tolist(),		clean_up_tokenization_spaces=lowerCAmelCase,		skip_special_tokens=lowerCAmelCase  )
              assert generated == expected_en






"""simple docstring"""





from diffusers.utils.testing_utils import require_onnxruntime


@require_onnxruntime
class A_	:




  '''simple docstring'''
  pass


