

'''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       UpperCamelCase(     UpperCAmelCase_  ,       UpperCAmelCase_  ,       UpperCAmelCase_  ,       UpperCAmelCase_=None  ,       UpperCAmelCase_=None  ,       UpperCAmelCase_=None  ,       UpperCAmelCase_=None  ,       UpperCAmelCase_=None  ,       ):
 if attention_mask is None:
  UpperCAmelCase       :	int											= input_ids.ne(config.pad_token_id	)
 if decoder_attention_mask is None:
  UpperCAmelCase       :	List[str]											= decoder_input_ids.ne(config.pad_token_id	)
 if head_mask is None:
  UpperCAmelCase       :	Optional[int]											= torch.ones(config.encoder_layers  ,       config.encoder_attention_heads  ,       device=UpperCAmelCase_	)
 if decoder_head_mask is None:
  UpperCAmelCase       :	Optional[Any]											= torch.ones(config.decoder_layers  ,       config.decoder_attention_heads  ,       device=UpperCAmelCase_	)
 if cross_attn_head_mask is None:
  UpperCAmelCase       :	List[Any]											= 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_ :






     '''simple docstring'''



     def __init__(		self :     int     ,			lowercase_ :     List[Any]     ,			lowercase_ :     List[str]=13     ,			lowercase_ :     Optional[Any]=7     ,			lowercase_ :     str=True     ,			lowercase_ :     Optional[int]=False     ,			lowercase_ :     int=99     ,			lowercase_ :     Any=16     ,			lowercase_ :     List[Any]=2     ,			lowercase_ :     int=4     ,			lowercase_ :     List[Any]=4     ,			lowercase_ :     List[str]="relu"     ,			lowercase_ :     List[Any]=0.1     ,			lowercase_ :     Union[str, Any]=0.1     ,			lowercase_ :     Union[str, Any]=0.0     ,			lowercase_ :     Tuple=0.0     ,			lowercase_ :     Optional[Any]=20     ,			lowercase_ :     Tuple=2     ,			lowercase_ :     List[Any]=1     ,			lowercase_ :     str=0     ,			)						->	Optional[Any]:
      UpperCAmelCase       :	int											= parent
      UpperCAmelCase       :	Any											= batch_size
      UpperCAmelCase       :	Optional[Any]											= seq_length
      UpperCAmelCase       :	int											= is_training
      UpperCAmelCase       :	Optional[Any]											= use_labels
      UpperCAmelCase       :	List[Any]											= vocab_size
      UpperCAmelCase       :	str											= hidden_size
      UpperCAmelCase       :	str											= num_hidden_layers
      UpperCAmelCase       :	List[str]											= num_attention_heads
      UpperCAmelCase       :	Optional[Any]											= intermediate_size
      UpperCAmelCase       :	int											= hidden_act
      UpperCAmelCase       :	Optional[int]											= hidden_dropout_prob
      UpperCAmelCase       :	Dict											= attention_probs_dropout_prob
      UpperCAmelCase       :	Tuple											= encoder_layerdrop
      UpperCAmelCase       :	Dict											= decoder_layerdrop
      UpperCAmelCase       :	Optional[Any]											= max_position_embeddings
      UpperCAmelCase       :	Any											= eos_token_id
      UpperCAmelCase       :	Optional[Any]											= pad_token_id
      UpperCAmelCase       :	Dict											= bos_token_id


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

      UpperCAmelCase       :	Optional[int]											= self.get_config()
      UpperCAmelCase       :	Union[str, Any]											= prepare_mam_aaa_inputs_dict(_lowerCAmelCase     ,			_lowerCAmelCase     ,			_lowerCAmelCase       )
      return config, inputs_dict


     def    UpperCAmelCase_       (		self :     Union[str, Any]       )						->	Union[str, 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    UpperCAmelCase_       (		self :     Dict       )						->	Union[str, Any]:
      UpperCAmelCase       :	List[str]											= self.prepare_config_and_inputs()
      return config, inputs_dict


     def    UpperCAmelCase_       (		self :     int     ,			lowercase_ :     List[Any]     ,			lowercase_ :     Optional[Any]       )						->	int:
      UpperCAmelCase       :	Union[str, Any]											= MaMaaaModel(config=_lowerCAmelCase       ).get_decoder().to(_lowerCAmelCase       ).eval()
      UpperCAmelCase       :	Dict											= inputs_dict["input_ids"]
      UpperCAmelCase       :	List[Any]											= inputs_dict["attention_mask"]
      UpperCAmelCase       :	Tuple											= inputs_dict["head_mask"]

      # first forward pass
      UpperCAmelCase       :	Any											= model(_lowerCAmelCase     ,			attention_mask=_lowerCAmelCase     ,			head_mask=_lowerCAmelCase     ,			use_cache=_lowerCAmelCase       )

      UpperCAmelCase       :	Tuple											= outputs.to_tuple()

      # create hypothetical multiple next token and extent to next_input_ids
      UpperCAmelCase       :	Tuple											= ids_tensor((self.batch_size, 3)     ,			config.vocab_size       )
      UpperCAmelCase       :	List[Any]											= ids_tensor((self.batch_size, 3)     ,			2       )

      # append to next input_ids and
      UpperCAmelCase       :	List[Any]											= torch.cat([input_ids, next_tokens]     ,			dim=-1       )
      UpperCAmelCase       :	Optional[int]											= torch.cat([attention_mask, next_attn_mask]     ,			dim=-1       )

      UpperCAmelCase       :	List[Any]											= model(_lowerCAmelCase     ,			attention_mask=_lowerCAmelCase       )["last_hidden_state"]
      UpperCAmelCase       :	List[str]											= model(_lowerCAmelCase     ,			attention_mask=_lowerCAmelCase     ,			past_key_values=_lowerCAmelCase       )[
          "last_hidden_state"
      ]

      # select random slice
      UpperCAmelCase       :	str											= ids_tensor((1,)     ,			output_from_past.shape[-1]       ).item()
      UpperCAmelCase       :	Tuple											= output_from_no_past[:, -3:, random_slice_idx].detach()
      UpperCAmelCase       :	Union[str, Any]											= 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    UpperCAmelCase_       (		self :     int     ,			lowercase_ :     Dict     ,			lowercase_ :     Any       )						->	Optional[int]:
      UpperCAmelCase       :	Optional[Any]											= MaMaaaModel(config=_lowerCAmelCase       ).to(_lowerCAmelCase       ).eval()
      UpperCAmelCase       :	str											= model(**_lowerCAmelCase       )

      UpperCAmelCase       :	int											= outputs.encoder_last_hidden_state
      UpperCAmelCase       :	Dict											= outputs.last_hidden_state

      with tempfile.TemporaryDirectory() as tmpdirname:
       UpperCAmelCase       :	Any											= model.get_encoder()
       encoder.save_pretrained(_lowerCAmelCase       )
       UpperCAmelCase       :	List[Any]											= MaMaaaEncoder.from_pretrained(_lowerCAmelCase       ).to(_lowerCAmelCase       )

      UpperCAmelCase       :	Optional[Any]											= 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       :	Union[str, Any]											= model.get_decoder()
       decoder.save_pretrained(_lowerCAmelCase       )
       UpperCAmelCase       :	Any											= MaMaaaDecoder.from_pretrained(_lowerCAmelCase       ).to(_lowerCAmelCase       )

      UpperCAmelCase       :	Any											= 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        A_ (				_snake_case       ,   _snake_case       ,   _snake_case       ,   unittest.TestCase							):






     '''simple docstring'''



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


     def    UpperCAmelCase_       (		self :     int     ,			lowercase_ :     List[str]     ,			lowercase_ :     Optional[int]     ,			lowercase_ :     List[str]     ,			lowercase_ :     Tuple     ,			lowercase_ :     Optional[int]       )						->	List[Any]:
      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    UpperCAmelCase_       (		self :     Any       )						->	Optional[int]:
      UpperCAmelCase       :	List[Any]											= MaMaaaModelTester(self       )
      UpperCAmelCase       :	Optional[int]											= ConfigTester(self     ,			config_class=_lowerCAmelCase       )


     def    UpperCAmelCase_       (		self :     Optional[int]       )						->	List[Any]:
      self.config_tester.run_common_tests()


     def    UpperCAmelCase_       (		self :     Union[str, Any]       )						->	Optional[Any]:
      UpperCAmelCase       :	Union[str, Any]											= self.model_tester.prepare_config_and_inputs()
      for model_class in self.all_model_classes:
       UpperCAmelCase       :	Dict											= model_class(_lowerCAmelCase       )

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


     def    UpperCAmelCase_       (		self :     Tuple       )						->	str:
      UpperCAmelCase       :	List[str]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_decoder_model_past_large_inputs(*_lowerCAmelCase       )


     def    UpperCAmelCase_       (		self :     int       )						->	Optional[Any]:
      UpperCAmelCase       :	str											= self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.check_encoder_decoder_model_standalone(*_lowerCAmelCase       )


     def    UpperCAmelCase_       (		self :     Tuple       )						->	str:
      UpperCAmelCase       :	int											= self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
       UpperCAmelCase       :	Union[str, Any]											= model_class(_lowerCAmelCase       )
       model.to(_lowerCAmelCase       )
       model.eval()

       UpperCAmelCase       :	Optional[int]											= copy.deepcopy(self._prepare_for_class(_lowerCAmelCase     ,			_lowerCAmelCase       )       )

       if not self.is_encoder_decoder:
        UpperCAmelCase       :	List[str]											= inputs["input_ids"]
        del inputs["input_ids"]
       else:
        UpperCAmelCase       :	Optional[int]											= inputs["input_ids"]
        UpperCAmelCase       :	List[str]											= inputs.get('decoder_input_ids'     ,			_lowerCAmelCase       )
        del inputs["input_ids"]
        inputs.pop('decoder_input_ids'     ,			_lowerCAmelCase       )

       UpperCAmelCase       :	Optional[int]											= model.get_input_embeddings()
       if not self.is_encoder_decoder:
        UpperCAmelCase       :	Tuple											= wte(_lowerCAmelCase       )
       else:
        UpperCAmelCase       :	Tuple											= wte(_lowerCAmelCase       )
        UpperCAmelCase       :	Dict											= wte(_lowerCAmelCase       )

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




     def    UpperCAmelCase_       (		self :     Any       )						->	Union[str, Any]:
      UpperCAmelCase       :	Optional[int]											= self.model_tester.prepare_config_and_inputs()
      UpperCAmelCase       :	Optional[int]											= input_dict["input_ids"]
      UpperCAmelCase       :	str											= input_ids.ne(1       ).to(_lowerCAmelCase       )
      UpperCAmelCase       :	int											= 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       UpperCamelCase(     UpperCAmelCase_	):
 return torch.tensor(UpperCAmelCase_  ,       dtype=torch.long  ,       device=UpperCAmelCase_	)


lowercase__			    =			1e-4




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






     '''simple docstring'''



     @cached_property
     def    UpperCAmelCase_       (		self :     Union[str, Any]       )						->	int:
      return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'       )


     def    UpperCAmelCase_       (		self :     Union[str, Any]       )						->	Union[str, Any]:
      UpperCAmelCase       :	List[str]											= MaMaaaModel.from_pretrained('facebook/m2m100_418M'       ).to(_lowerCAmelCase       )
      UpperCAmelCase       :	List[str]											= _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]       )
      UpperCAmelCase       :	Tuple											= _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]       )
      UpperCAmelCase       :	str											= prepare_mam_aaa_inputs_dict(model.config     ,			_lowerCAmelCase     ,			_lowerCAmelCase       )
      with torch.no_grad():
       UpperCAmelCase       :	Tuple											= model(**_lowerCAmelCase       )[0]
      UpperCAmelCase       :	List[str]											= torch.Size((1, 11, 1_024)       )
      self.assertEqual(output.shape     ,			_lowerCAmelCase       )
      # change to expected output here
      UpperCAmelCase       :	Tuple											= 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    UpperCAmelCase_       (		self :     Optional[int]       )						->	Any:
      UpperCAmelCase       :	str											= MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'       ).to(_lowerCAmelCase       )

      # change to intended input
      UpperCAmelCase       :	Tuple											= _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]       )
      UpperCAmelCase       :	Optional[Any]											= _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]       )
      UpperCAmelCase       :	Any											= prepare_mam_aaa_inputs_dict(model.config     ,			_lowerCAmelCase     ,			_lowerCAmelCase       )
      with torch.no_grad():
       UpperCAmelCase       :	List[Any]											= model(**_lowerCAmelCase       )[0]
      UpperCAmelCase       :	Union[str, Any]											= torch.Size((1, 11, model.config.vocab_size)       )
      self.assertEqual(output.shape     ,			_lowerCAmelCase       )
      # change to expected output here
      UpperCAmelCase       :	Union[str, Any]											= 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    UpperCAmelCase_       (		self :     Tuple       )						->	str:
      UpperCAmelCase       :	List[str]											= MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'       ).to(_lowerCAmelCase       )
      UpperCAmelCase       :	List[Any]											= MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'     ,			src_lang='fr'     ,			tgt_lang='en'       )

      UpperCAmelCase       :	Tuple											= [
          "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       :	str											= tokenizer(_lowerCAmelCase     ,			padding=_lowerCAmelCase     ,			return_tensors='pt'       )

      UpperCAmelCase       :	Optional[int]											= 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'       )     ,			)

      UpperCAmelCase       :	Dict											= [
          "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       :	Union[str, Any]											= tokenizer.batch_decode(
          hypotheses_batch.tolist()     ,			clean_up_tokenization_spaces=_lowerCAmelCase     ,			skip_special_tokens=_lowerCAmelCase       )
      assert generated == expected_en










_UpperCAmelCase		:  Tuple	=   {str(digit): digit**5 for digit in range(10)}



def 					UpperCAmelCase__     (   lowerCamelCase      ):
  return sum(DIGITS_FIFTH_POWER[digit] for digit in str(lowerCamelCase      )      )



def 					UpperCAmelCase__     (   ):
  return sum(
      number
      for number in range(1000,	1000000      )
      if number == digits_fifth_powers_sum(lowerCamelCase      )      )


if __name__ == "__main__":
     print(solution())



