

"""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  (  UpperCamelCase_					:	Union[str, Any],      UpperCamelCase_					:	str,      UpperCamelCase_					:	int,      UpperCamelCase_					:	int=None,      UpperCamelCase_					:	Dict=None,      UpperCamelCase_					:	Optional[int]=None,      UpperCamelCase_					:	Optional[Any]=None,      UpperCamelCase_					:	Tuple=None,      )     ->						Optional[int]:
   '''simple docstring'''


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







 """simple docstring"""







 def __init__(      self							:      Tuple, UpperCAmelCase__							:      str, UpperCAmelCase__							:      int=1_3, UpperCAmelCase__							:      Optional[Any]=7, UpperCAmelCase__							:      Any=True, UpperCAmelCase__							:      List[Any]=False, UpperCAmelCase__							:      Optional[Any]=9_9, UpperCAmelCase__							:      Dict=1_6, UpperCAmelCase__							:      str=2, UpperCAmelCase__							:      Any=4, UpperCAmelCase__							:      Tuple=4, UpperCAmelCase__							:      List[str]="relu", UpperCAmelCase__							:      Dict=0.1, UpperCAmelCase__							:      str=0.1, UpperCAmelCase__							:      Union[str, Any]=0.0, UpperCAmelCase__							:      Tuple=0.0, UpperCAmelCase__							:      Optional[Any]=2_0, UpperCAmelCase__							:      Any=2, UpperCAmelCase__							:      Any=1, UpperCAmelCase__							:      Optional[Any]=0, ):
    __lowercase								=						parent
    __lowercase								=						batch_size
    __lowercase								=						seq_length
    __lowercase								=						is_training
    __lowercase								=						use_labels
    __lowercase								=						vocab_size
    __lowercase								=						hidden_size
    __lowercase								=						num_hidden_layers
    __lowercase								=						num_attention_heads
    __lowercase								=						intermediate_size
    __lowercase								=						hidden_act
    __lowercase								=						hidden_dropout_prob
    __lowercase								=						attention_probs_dropout_prob
    __lowercase								=						encoder_layerdrop
    __lowercase								=						decoder_layerdrop
    __lowercase								=						max_position_embeddings
    __lowercase								=						eos_token_id
    __lowercase								=						pad_token_id
    __lowercase								=						bos_token_id


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

    __lowercase								=						self.get_config()
    __lowercase								=						prepare_mam_aaa_inputs_dict(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__     )
    return config, inputs_dict


 def  _lowercase			(      self							:      str     ):
    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							:      str     ):
    __lowercase								=						self.prepare_config_and_inputs()
    return config, inputs_dict


 def  _lowercase			(      self							:      str, UpperCAmelCase__							:      Any, UpperCAmelCase__							:      Union[str, Any]     ):
    __lowercase								=						MaMaaaModel(config=UpperCAmelCase__     ).get_decoder().to(UpperCAmelCase__     ).eval()
    __lowercase								=						inputs_dict['input_ids']
    __lowercase								=						inputs_dict['attention_mask']
    __lowercase								=						inputs_dict['head_mask']

    # first forward pass
    __lowercase								=						model(UpperCAmelCase__, attention_mask=UpperCAmelCase__, head_mask=UpperCAmelCase__, use_cache=UpperCAmelCase__     )

    __lowercase								=						outputs.to_tuple()

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

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

    __lowercase								=						model(UpperCAmelCase__, attention_mask=UpperCAmelCase__     )['last_hidden_state']
    __lowercase								=						model(UpperCAmelCase__, attention_mask=UpperCAmelCase__, past_key_values=UpperCAmelCase__     )[
        'last_hidden_state'
    ]

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

    __lowercase								=						outputs.encoder_last_hidden_state
    __lowercase								=						outputs.last_hidden_state

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

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

    __lowercase								=						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  _lowerCAmelCase  (     __UpperCamelCase					,__UpperCamelCase					,__UpperCamelCase					,unittest.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : Optional[int]       		=     (
     (
         MaMaaaModel,
         MaMaaaForConditionalGeneration,
     )
     if is_torch_available()
     else ()
 )
 __UpperCAmelCase     : Tuple       		=     (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
 __UpperCAmelCase     : List[Any]       		=     (
     {
         "conversational": MaMaaaForConditionalGeneration,
         "feature-extraction": MaMaaaModel,
         "summarization": MaMaaaForConditionalGeneration,
         "text2text-generation": MaMaaaForConditionalGeneration,
         "translation": MaMaaaForConditionalGeneration,
     }
     if is_torch_available()
     else {}
 )
 __UpperCAmelCase     : Dict       		=     True
 __UpperCAmelCase     : Optional[Any]       		=     True
 __UpperCAmelCase     : Dict       		=     False
 __UpperCAmelCase     : Optional[Any]       		=     False


 def  _lowercase			(      self							:      Tuple, UpperCAmelCase__							:      str, UpperCAmelCase__							:      str, UpperCAmelCase__							:      int, UpperCAmelCase__							:      Dict, UpperCAmelCase__							:      int     ):
    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							:      Any     ):
    __lowercase								=						MaMaaaModelTester(self     )
    __lowercase								=						ConfigTester(self, config_class=UpperCAmelCase__     )


 def  _lowercase			(      self							:      int     ):
    self.config_tester.run_common_tests()


 def  _lowercase			(      self							:      Union[str, Any]     ):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    for model_class in self.all_model_classes:
       __lowercase								=						model_class(UpperCAmelCase__     )

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


 def  _lowercase			(      self							:      Optional[int]     ):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__     )


 def  _lowercase			(      self							:      Tuple     ):
    __lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()
    self.model_tester.check_encoder_decoder_model_standalone(*UpperCAmelCase__     )


 def  _lowercase			(      self							:      Union[str, Any]     ):
    __lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
       __lowercase								=						model_class(UpperCAmelCase__     )
       model.to(UpperCAmelCase__     )
       model.eval()

       __lowercase								=						copy.deepcopy(self._prepare_for_class(UpperCAmelCase__, UpperCAmelCase__     )     )

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

       __lowercase								=						model.get_input_embeddings()
       if not self.is_encoder_decoder:
          __lowercase								=						wte(UpperCAmelCase__     )
       else:
          __lowercase								=						wte(UpperCAmelCase__     )
          __lowercase								=						wte(UpperCAmelCase__     )

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



 def  _lowercase			(      self							:      Tuple     ):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    __lowercase								=						input_dict['input_ids']
    __lowercase								=						input_ids.ne(1     ).to(UpperCAmelCase__     )
    __lowercase								=						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  (  UpperCamelCase_					:	Optional[int])     ->						Optional[Any]:
   '''simple docstring'''


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


_a							=							1e-4




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







 """simple docstring"""







 @cached_property
 def  _lowercase			(      self							:      int     ):
    return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"     )


 def  _lowercase			(      self							:      Optional[int]     ):
    __lowercase								=						MaMaaaModel.from_pretrained("facebook/m2m100_418M"     ).to(UpperCAmelCase__     )
    __lowercase								=						_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]     )
    __lowercase								=						_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]     )
    __lowercase								=						prepare_mam_aaa_inputs_dict(model.config, UpperCAmelCase__, UpperCAmelCase__     )
    with torch.no_grad():
       __lowercase								=						model(**UpperCAmelCase__     )[0]
    __lowercase								=						torch.Size((1, 1_1, 1_0_2_4)     )
    self.assertEqual(output.shape, UpperCAmelCase__     )
    # change to expected output here
    __lowercase								=						torch.tensor(
        [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]], device=UpperCAmelCase__     )
    self.assertTrue(torch.allclose(output[:, :3, :3], UpperCAmelCase__, atol=UpperCAmelCase__     )     )


 def  _lowercase			(      self							:      str     ):
    __lowercase								=						MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"     ).to(UpperCAmelCase__     )

    # change to intended input
    __lowercase								=						_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]     )
    __lowercase								=						_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]     )
    __lowercase								=						prepare_mam_aaa_inputs_dict(model.config, UpperCAmelCase__, UpperCAmelCase__     )
    with torch.no_grad():
       __lowercase								=						model(**UpperCAmelCase__     )[0]
    __lowercase								=						torch.Size((1, 1_1, model.config.vocab_size)     )
    self.assertEqual(output.shape, UpperCAmelCase__     )
    # change to expected output here
    __lowercase								=						torch.tensor(
        [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]], device=UpperCAmelCase__     )
    self.assertTrue(torch.allclose(output[:, :3, :3], UpperCAmelCase__, atol=UpperCAmelCase__     )     )



 def  _lowercase			(      self							:      Optional[int]     ):
    __lowercase								=						MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"     ).to(UpperCAmelCase__     )
    __lowercase								=						MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M", src_lang="fr", tgt_lang="en"     )

    __lowercase								=						[
        '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
    __lowercase								=						tokenizer(UpperCAmelCase__, padding=UpperCAmelCase__, return_tensors="pt"     )

    __lowercase								=						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"     ), )

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

    __lowercase								=						tokenizer.batch_decode(
        hypotheses_batch.tolist(), clean_up_tokenization_spaces=UpperCAmelCase__, skip_special_tokens=UpperCAmelCase__     )
    assert generated == expected_en


"""simple docstring"""





import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812




def   _A  (  )     ->						None:
   '''simple docstring'''


   print("Making key files...")
   make_key_files("rsa",      1024)
   print("Key files generation successful.")




def   _A  (  UpperCamelCase_					:	int)     ->						tuple[tuple[int, int], tuple[int, int]]:
   '''simple docstring'''


   print("Generating prime p...")
   __lowercase								=						rabinMiller.generate_large_prime(UpperCamelCase_)
   print("Generating prime q...")
   __lowercase								=						rabinMiller.generate_large_prime(UpperCamelCase_)
   __lowercase								=						p * q

   print("Generating e that is relatively prime to (p - 1) * (q - 1)...")
   while True:
      __lowercase								=						random.randrange(2 ** (key_size - 1),      2 ** (key_size))
      if cryptoMath.gcd(UpperCamelCase_,      (p - 1) * (q - 1)) == 1:
         break

   print("Calculating d that is mod inverse of e...")
   __lowercase								=						cryptoMath.find_mod_inverse(UpperCamelCase_,      (p - 1) * (q - 1))

   __lowercase								=						(n, e)
   __lowercase								=						(n, d)
   return (public_key, private_key)




def   _A  (  UpperCamelCase_					:	str,      UpperCamelCase_					:	int)     ->						None:
   '''simple docstring'''


   if os.path.exists(F"""{name}_pubkey.txt""") or os.path.exists(F"""{name}_privkey.txt"""):
      print("\nWARNING:")
      print(
          F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"""
          "Use a different name or delete these files and re-run this program.")
      sys.exit()

   __lowercase		,__lowercase								=						generate_key(UpperCamelCase_)
   print(F"""\nWriting public key to file {name}_pubkey.txt...""")
   with open(F"""{name}_pubkey.txt""",      "w") as out_file:
      out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""")

   print(F"""Writing private key to file {name}_privkey.txt...""")
   with open(F"""{name}_privkey.txt""",      "w") as out_file:
      out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""")


if __name__ == "__main__":
   main()




