



"""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__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=None     ,      ):
      if attention_mask is None:
            UpperCAmelCase_      			=							input_ids.ne(config.pad_token_id				)
      if decoder_attention_mask is None:
            UpperCAmelCase_      			=							decoder_input_ids.ne(config.pad_token_id				)
      if head_mask is None:
            UpperCAmelCase_      			=							torch.ones(config.encoder_layers     ,      config.encoder_attention_heads     ,      device=lowerCAmelCase__				)
      if decoder_head_mask is None:
            UpperCAmelCase_      			=							torch.ones(config.decoder_layers     ,      config.decoder_attention_heads     ,      device=lowerCAmelCase__				)
      if cross_attn_head_mask is None:
            UpperCAmelCase_      			=							torch.ones(config.decoder_layers     ,      config.decoder_attention_heads     ,      device=lowerCAmelCase__				)
      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__       :







       '''simple docstring'''


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


             '''simple docstring'''




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



       def 					lowercase__    (							self      :  Optional[Any]   )			->						Union[str, Any]:


             '''simple docstring'''




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

             UpperCAmelCase_      			=							self.get_config()
             UpperCAmelCase_      			=							prepare_mam_aaa_inputs_dict(_UpperCAmelCase		,    _UpperCAmelCase		,    _UpperCAmelCase   )
             return config, inputs_dict



       def 					lowercase__    (							self      :  str   )			->						List[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 					lowercase__    (							self      :  List[Any]   )			->						Union[str, Any]:


             '''simple docstring'''




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



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  List[Any]		,    _UpperCAmelCase      :  Optional[Any]   )			->						Optional[Any]:


             '''simple docstring'''




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

             # first forward pass
             UpperCAmelCase_      			=							model(_UpperCAmelCase		,    attention_mask=_UpperCAmelCase		,    head_mask=_UpperCAmelCase		,    use_cache=_UpperCAmelCase   )

             UpperCAmelCase_			,   UpperCAmelCase_      			=							outputs.to_tuple()

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

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

             UpperCAmelCase_      			=							model(_UpperCAmelCase		,    attention_mask=_UpperCAmelCase   )["last_hidden_state"]
             UpperCAmelCase_      			=							model(_UpperCAmelCase		,    attention_mask=_UpperCAmelCase		,    past_key_values=_UpperCAmelCase   )[
                 "last_hidden_state"
             ]

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







       def 					lowercase__    (							self      :  str		,    _UpperCAmelCase      :  Optional[int]		,    _UpperCAmelCase      :  Any   )			->						List[str]:


             '''simple docstring'''




             UpperCAmelCase_      			=							MaMaaaModel(config=_UpperCAmelCase   ).to(_UpperCAmelCase   ).eval()
             UpperCAmelCase_      			=							model(**_UpperCAmelCase   )

             UpperCAmelCase_      			=							outputs.encoder_last_hidden_state
             UpperCAmelCase_      			=							outputs.last_hidden_state

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

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

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







       '''simple docstring'''


       UpperCamelCase						=					(
           (
               MaMaaaModel,
               MaMaaaForConditionalGeneration,
           )
           if is_torch_available()
           else ()
       )
       UpperCamelCase						=					(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
       UpperCamelCase						=					(
           {
               '''conversational''': MaMaaaForConditionalGeneration,
               '''feature-extraction''': MaMaaaModel,
               '''summarization''': MaMaaaForConditionalGeneration,
               '''text2text-generation''': MaMaaaForConditionalGeneration,
               '''translation''': MaMaaaForConditionalGeneration,
           }
           if is_torch_available()
           else {}
       )
       UpperCamelCase						=					True
       UpperCamelCase						=					True
       UpperCamelCase						=					False
       UpperCamelCase						=					False



       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  List[str]		,    _UpperCAmelCase      :  List[Any]   )			->						Tuple:


             '''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      :  List[Any]   )			->						int:


             '''simple docstring'''




             UpperCAmelCase_      			=							MaMaaaModelTester(self   )
             UpperCAmelCase_      			=							ConfigTester(self		,    config_class=_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Optional[Any]   )			->						List[Any]:


             '''simple docstring'''




             self.config_tester.run_common_tests()



       def 					lowercase__    (							self      :  Optional[int]   )			->						int:


             '''simple docstring'''




             UpperCAmelCase_			,   UpperCAmelCase_      			=							self.model_tester.prepare_config_and_inputs()
             for model_class in self.all_model_classes:
                   UpperCAmelCase_      			=							model_class(_UpperCAmelCase   )

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



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


             '''simple docstring'''




             UpperCAmelCase_      			=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_decoder_model_past_large_inputs(*_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Union[str, Any]   )			->						int:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.check_encoder_decoder_model_standalone(*_UpperCAmelCase   )



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


             '''simple docstring'''




             UpperCAmelCase_			,   UpperCAmelCase_      			=							self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
                   UpperCAmelCase_      			=							model_class(_UpperCAmelCase   )
                   model.to(_UpperCAmelCase   )
                   model.eval()

                   UpperCAmelCase_      			=							copy.deepcopy(self._prepare_for_class(_UpperCAmelCase		,    _UpperCAmelCase   )   )

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

                   UpperCAmelCase_      			=							model.get_input_embeddings()
                   if not self.is_encoder_decoder:
                         UpperCAmelCase_      			=							wte(_UpperCAmelCase   )
                   else:
                         UpperCAmelCase_      			=							wte(_UpperCAmelCase   )
                         UpperCAmelCase_      			=							wte(_UpperCAmelCase   )

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







       def 					lowercase__    (							self      :  Tuple   )			->						Optional[Any]:


             '''simple docstring'''




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



def        a__     (				lowerCAmelCase__				):
      return torch.tensor(lowerCAmelCase__     ,      dtype=torch.long     ,      device=lowerCAmelCase__				)


lowerCamelCase       	=						1e-4


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







       '''simple docstring'''


       @cached_property
       def 					lowercase__    (							self      :  Optional[int]   )			->						Union[str, Any]:


             '''simple docstring'''




             return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"   )



       def 					lowercase__    (							self      :  List[str]   )			->						Dict:


             '''simple docstring'''




             UpperCAmelCase_      			=							MaMaaaModel.from_pretrained("facebook/m2m100_418M"   ).to(_UpperCAmelCase   )
             UpperCAmelCase_      			=							_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]   )
             UpperCAmelCase_      			=							_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]   )
             UpperCAmelCase_      			=							prepare_mam_aaa_inputs_dict(model.config		,    _UpperCAmelCase		,    _UpperCAmelCase   )
             with torch.no_grad():
                   UpperCAmelCase_      			=							model(**_UpperCAmelCase   )[0]
             UpperCAmelCase_      			=							torch.Size((1, 11, 1024)   )
             self.assertEqual(output.shape		,    _UpperCAmelCase   )
             # change to expected output here
             UpperCAmelCase_      			=							torch.tensor(
                 [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]		,    device=_UpperCAmelCase   )
             self.assertTrue(torch.allclose(output[:, :3, :3]		,    _UpperCAmelCase		,    atol=_UpperCAmelCase   )   )



       def 					lowercase__    (							self      :  str   )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"   ).to(_UpperCAmelCase   )

             # change to intended input
             UpperCAmelCase_      			=							_long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]   )
             UpperCAmelCase_      			=							_long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]   )
             UpperCAmelCase_      			=							prepare_mam_aaa_inputs_dict(model.config		,    _UpperCAmelCase		,    _UpperCAmelCase   )
             with torch.no_grad():
                   UpperCAmelCase_      			=							model(**_UpperCAmelCase   )[0]
             UpperCAmelCase_      			=							torch.Size((1, 11, model.config.vocab_size)   )
             self.assertEqual(output.shape		,    _UpperCAmelCase   )
             # change to expected output here
             UpperCAmelCase_      			=							torch.tensor(
                 [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]		,    device=_UpperCAmelCase   )
             self.assertTrue(torch.allclose(output[:, :3, :3]		,    _UpperCAmelCase		,    atol=_UpperCAmelCase   )   )







       def 					lowercase__    (							self      :  Dict   )			->						Tuple:


             '''simple docstring'''




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

             UpperCAmelCase_      			=							[
                 "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_      			=							tokenizer(_UpperCAmelCase		,    padding=_UpperCAmelCase		,    return_tensors="pt"   )

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

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









"""simple docstring"""





def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__				):
      return [sentence[i : i + ngram_size] for i in range(len(lowerCAmelCase__				) - ngram_size + 1				)]


if __name__ == "__main__":
  from doctest import testmod

  testmod()




