



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



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


           '''simple docstring'''

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



       def 		_lowerCamelCase      (		self							:					Tuple):


           '''simple docstring'''

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

           __a							=    self.get_config()
           __a							=    prepare_mam_aaa_inputs_dict(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE)
           return config, inputs_dict



       def 		_lowerCamelCase      (		self							:					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 		_lowerCamelCase      (		self							:					str):


           '''simple docstring'''

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



       def 		_lowerCamelCase      (		self							:					str					,		__SCREAMING_SNAKE_CASE							:					Union[str, Any]					,		__SCREAMING_SNAKE_CASE							:					List[Any]):


           '''simple docstring'''

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

           # first forward pass
           __a							=    model(__SCREAMING_SNAKE_CASE					,		attention_mask=__SCREAMING_SNAKE_CASE					,		head_mask=__SCREAMING_SNAKE_CASE					,		use_cache=__SCREAMING_SNAKE_CASE)

           __a	,       __a							=    outputs.to_tuple()

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

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

           __a							=    model(__SCREAMING_SNAKE_CASE					,		attention_mask=__SCREAMING_SNAKE_CASE)['''last_hidden_state''']
           __a							=    model(__SCREAMING_SNAKE_CASE					,		attention_mask=__SCREAMING_SNAKE_CASE					,		past_key_values=__SCREAMING_SNAKE_CASE)[
               '''last_hidden_state'''
           ]

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





       def 		_lowerCamelCase      (		self							:					Optional[Any]					,		__SCREAMING_SNAKE_CASE							:					Optional[Any]					,		__SCREAMING_SNAKE_CASE							:					Optional[Any]):


           '''simple docstring'''

           __a							=    MaMaaaModel(config=__SCREAMING_SNAKE_CASE).to(__SCREAMING_SNAKE_CASE).eval()
           __a							=    model(**__SCREAMING_SNAKE_CASE)

           __a							=    outputs.encoder_last_hidden_state
           __a							=    outputs.last_hidden_state

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

           __a							=    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:
               __a							=    model.get_decoder()
               decoder.save_pretrained(__SCREAMING_SNAKE_CASE)
               __a							=    MaMaaaDecoder.from_pretrained(__SCREAMING_SNAKE_CASE).to(__SCREAMING_SNAKE_CASE)

           __a							=    decoder(
               input_ids=inputs_dict['''decoder_input_ids''']					,		attention_mask=inputs_dict['''decoder_attention_mask''']					,		encoder_hidden_states=__SCREAMING_SNAKE_CASE					,		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    _A	(     __UpperCAmelCase				,__UpperCAmelCase				,__UpperCAmelCase				,unittest.TestCase   ):
       UpperCamelCase__  :   str						 =						(
           (
               MaMaaaModel,
               MaMaaaForConditionalGeneration,
           )
           if is_torch_available()
           else ()
       )
       UpperCamelCase__  :   Dict						 =						(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
       UpperCamelCase__  :   Optional[Any]						 =						(
           {
               '''conversational''': MaMaaaForConditionalGeneration,
               '''feature-extraction''': MaMaaaModel,
               '''summarization''': MaMaaaForConditionalGeneration,
               '''text2text-generation''': MaMaaaForConditionalGeneration,
               '''translation''': MaMaaaForConditionalGeneration,
           }
           if is_torch_available()
           else {}
       )
       UpperCamelCase__  :   int						 =						True
       UpperCamelCase__  :   str						 =						True
       UpperCamelCase__  :   int						 =						False
       UpperCamelCase__  :   Optional[int]						 =						False



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


           '''simple docstring'''

           __a							=    MaMaaaModelTester(self)
           __a							=    ConfigTester(self					,		config_class=__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					Union[str, Any]):


           '''simple docstring'''

           self.config_tester.run_common_tests()



       def 		_lowerCamelCase      (		self							:					Union[str, Any]):


           '''simple docstring'''

           __a	,       __a							=    self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
               __a							=    model_class(__SCREAMING_SNAKE_CASE)

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



       def 		_lowerCamelCase      (		self							:					List[Any]):


           '''simple docstring'''

           __a							=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(*__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					str):


           '''simple docstring'''

           __a							=    self.model_tester.prepare_config_and_inputs_for_common()
           self.model_tester.check_encoder_decoder_model_standalone(*__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					int):


           '''simple docstring'''

           __a	,       __a							=    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
               __a							=    model_class(__SCREAMING_SNAKE_CASE)
               model.to(__SCREAMING_SNAKE_CASE)
               model.eval()

               __a							=    copy.deepcopy(self._prepare_for_class(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE))

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

               __a							=    model.get_input_embeddings()
               if not self.is_encoder_decoder:
                   __a							=    wte(__SCREAMING_SNAKE_CASE)
               else:
                   __a							=    wte(__SCREAMING_SNAKE_CASE)
                   __a							=    wte(__SCREAMING_SNAKE_CASE)

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





       def 		_lowerCamelCase      (		self							:					Optional[Any]):


           '''simple docstring'''

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





def 					__snake_case     (      _UpperCAmelCase    ):
    return torch.tensor(_UpperCAmelCase       ,			dtype=torch.long       ,			device=_UpperCAmelCase    )


__snake_case						:Union[str, Any]						=					1E-4

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



       @cached_property
       def 		_lowerCamelCase      (		self							:					str):


           '''simple docstring'''

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



       def 		_lowerCamelCase      (		self							:					Tuple):


           '''simple docstring'''

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



       def 		_lowerCamelCase      (		self							:					Dict):


           '''simple docstring'''

           __a							=    MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M''').to(__SCREAMING_SNAKE_CASE)

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





       def 		_lowerCamelCase      (		self							:					List[str]):


           '''simple docstring'''

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

           __a							=    [
               '''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
           __a							=    tokenizer(__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		return_tensors='''pt''')

           __a							=    model.generate(
               input_ids=dct['''input_ids'''].to(__SCREAMING_SNAKE_CASE)					,		attention_mask=dct['''attention_mask'''].to(__SCREAMING_SNAKE_CASE)					,		num_beams=5					,		forced_bos_token_id=tokenizer.get_lang_id('''en''')					,		)

           __a							=    [
               '''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.''',
           ]

           __a							=    tokenizer.batch_decode(
               hypotheses_batch.tolist()					,		clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE					,		skip_special_tokens=__SCREAMING_SNAKE_CASE)
           assert generated == expected_en










def 					__snake_case     (      _UpperCAmelCase    ):
    if not isinstance(_UpperCAmelCase       ,			_UpperCAmelCase    ):
        raise TypeError('''Input value must be an \'int\' type'''    )

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

    return position


if __name__ == "__main__":
 import doctest

 doctest.testmod()





