





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



    '''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=SCREAMING_SNAKE_CASE_    )
    if decoder_head_mask is None:
        _lowerCAmelCase				=      torch.ones(config.decoder_layers		,       config.decoder_attention_heads		,       device=SCREAMING_SNAKE_CASE_    )
    if cross_attn_head_mask is None:
        _lowerCAmelCase				=      torch.ones(config.decoder_layers		,       config.decoder_attention_heads		,       device=SCREAMING_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    lowerCAmelCase_		:




 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			,     )    ->							Tuple:
     _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 							_snake_case   (	self		)    ->							Optional[int]:
     _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 							_snake_case   (	self		)    ->							List[Any]:
     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		)    ->							Optional[Any]:
     _lowerCAmelCase			,			_lowerCAmelCase				=      self.prepare_config_and_inputs()
     return config, inputs_dict




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase		)    ->							int:
     _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 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase		)    ->							int:
     _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    lowerCAmelCase_		(		__magic_name__						,__magic_name__						,__magic_name__						,unittest.TestCase		):
 __lowerCamelCase						:							Tuple         =					(
     (
         MaMaaaModel,
         MaMaaaForConditionalGeneration,
     )
     if is_torch_available()
     else ()
 )
 __lowerCamelCase						:							int         =					(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
 __lowerCamelCase						:							Union[str, Any]         =					(
     {
         "conversational": MaMaaaForConditionalGeneration,
         "feature-extraction": MaMaaaModel,
         "summarization": MaMaaaForConditionalGeneration,
         "text2text-generation": MaMaaaForConditionalGeneration,
         "translation": MaMaaaForConditionalGeneration,
     }
     if is_torch_available()
     else {}
 )
 __lowerCamelCase						:							Union[str, Any]         =					True
 __lowerCamelCase						:							List[str]         =					True
 __lowerCamelCase						:							Any         =					False
 __lowerCamelCase						:							Union[str, Any]         =					False




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase		)    ->							Tuple:
     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		)    ->							str:
     _lowerCAmelCase				=      MaMaaaModelTester(self		)
     _lowerCAmelCase				=      ConfigTester(self			,     config_class=_lowerCAmelCase		)




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




 def 							_snake_case   (	self		)    ->							Any:
     _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 							_snake_case   (	self		)    ->							List[str]:
     _lowerCAmelCase				=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_decoder_model_past_large_inputs(*_lowerCAmelCase		)




 def 							_snake_case   (	self		)    ->							str:
     _lowerCAmelCase				=      self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_encoder_decoder_model_standalone(*_lowerCAmelCase		)




 def 							_snake_case   (	self		)    ->							int:
     _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 							_snake_case   (	self		)    ->							Union[str, Any]:
     _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(SCREAMING_SNAKE_CASE_  :					Any    ):



    '''simple docstring'''





    return torch.tensor(SCREAMING_SNAKE_CASE_		,       dtype=torch.long		,       device=SCREAMING_SNAKE_CASE_    )


_SCREAMING_SNAKE_CASE	 =							1e-4





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




 @cached_property
 def 							_snake_case   (	self		)    ->							Dict:
     return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"		)




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




 def 							_snake_case   (	self		)    ->							Dict:
     _lowerCAmelCase				=      MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"		).to(_lowerCAmelCase		)

     # change to intended input
     _lowerCAmelCase				=      _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]		)
     _lowerCAmelCase				=      _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 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.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]			,     device=_lowerCAmelCase		)
     self.assertTrue(torch.allclose(output[:, :3, :3]			,     _lowerCAmelCase			,     atol=_lowerCAmelCase		)		)





 def 							_snake_case   (	self		)    ->							Tuple:
     _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'''


def 	__a(SCREAMING_SNAKE_CASE_  :					int    ):



    '''simple docstring'''





    if not isinstance(SCREAMING_SNAKE_CASE_		,       SCREAMING_SNAKE_CASE_    ):
        raise TypeError("Input value must be an 'int' type"    )

    _lowerCAmelCase				=      0
    while number:
        position += 1
        number >>= 1

    return position


if __name__ == "__main__":
       import doctest

       doctest.testmod()


