





"""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       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_=None  ,			UpperCAmelCase_=None  ,			UpperCAmelCase_=None  ,			UpperCAmelCase_=None  ,			UpperCAmelCase_=None  ,			)						->Optional[int]:





  """simple docstring"""


  if attention_mask is None:
    __UpperCAmelCase    :						Any       =						input_ids.ne(config.pad_token_id  )
  if decoder_attention_mask is None:
    __UpperCAmelCase    :						Dict       =						decoder_input_ids.ne(config.pad_token_id  )
  if head_mask is None:
    __UpperCAmelCase    :						List[Any]       =						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    :						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 							snake_case							:

      '''simple docstring'''



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


        '''simple docstring'''




        __UpperCAmelCase    :						List[str]       =						parent
        __UpperCAmelCase    :						Tuple       =						batch_size
        __UpperCAmelCase    :						Optional[int]       =						seq_length
        __UpperCAmelCase    :						Any       =						is_training
        __UpperCAmelCase    :						Optional[Any]       =						use_labels
        __UpperCAmelCase    :						int       =						vocab_size
        __UpperCAmelCase    :						List[str]       =						hidden_size
        __UpperCAmelCase    :						Dict       =						num_hidden_layers
        __UpperCAmelCase    :						Dict       =						num_attention_heads
        __UpperCAmelCase    :						Optional[Any]       =						intermediate_size
        __UpperCAmelCase    :						int       =						hidden_act
        __UpperCAmelCase    :						Dict       =						hidden_dropout_prob
        __UpperCAmelCase    :						Optional[int]       =						attention_probs_dropout_prob
        __UpperCAmelCase    :						Any       =						encoder_layerdrop
        __UpperCAmelCase    :						List[str]       =						decoder_layerdrop
        __UpperCAmelCase    :						Tuple       =						max_position_embeddings
        __UpperCAmelCase    :						Optional[Any]       =						eos_token_id
        __UpperCAmelCase    :						Tuple       =						pad_token_id
        __UpperCAmelCase    :						str       =						bos_token_id

      def       A_					(							self       :      Dict ):


        '''simple docstring'''




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

        __UpperCAmelCase    :						List[Any]       =						self.get_config()
        __UpperCAmelCase    :						Tuple       =						prepare_mam_aaa_inputs_dict(__lowercase						,				__lowercase						,				__lowercase )
        return config, inputs_dict

      def       A_					(							self       :      Any ):


        '''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       A_					(							self       :      Dict ):


        '''simple docstring'''




        __UpperCAmelCase       ,     __UpperCAmelCase    :						Optional[int]       =						self.prepare_config_and_inputs()
        return config, inputs_dict

      def       A_					(							self       :      str						,				__lowercase       :      Optional[int]						,				__lowercase       :      List[Any] ):


        '''simple docstring'''




        __UpperCAmelCase    :						List[Any]       =						MaMaaaModel(config=__lowercase ).get_decoder().to(__lowercase ).eval()
        __UpperCAmelCase    :						Optional[Any]       =						inputs_dict['''input_ids''']
        __UpperCAmelCase    :						Dict       =						inputs_dict['''attention_mask''']
        __UpperCAmelCase    :						List[Any]       =						inputs_dict['''head_mask''']

        # first forward pass
        __UpperCAmelCase    :						Dict       =						model(__lowercase						,				attention_mask=__lowercase						,				head_mask=__lowercase						,				use_cache=__lowercase )

        __UpperCAmelCase       ,     __UpperCAmelCase    :						Optional[int]       =						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    :						Any       =						ids_tensor((self.batch_size, 3)						,				2 )

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

        __UpperCAmelCase    :						Dict       =						model(__lowercase						,				attention_mask=__lowercase )['''last_hidden_state''']
        __UpperCAmelCase    :						List[Any]       =						model(__lowercase						,				attention_mask=__lowercase						,				past_key_values=__lowercase )[
            '''last_hidden_state'''
        ]

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







      def       A_					(							self       :      int						,				__lowercase       :      Dict						,				__lowercase       :      Optional[Any] ):


        '''simple docstring'''




        __UpperCAmelCase    :						Tuple       =						MaMaaaModel(config=__lowercase ).to(__lowercase ).eval()
        __UpperCAmelCase    :						Optional[int]       =						model(**__lowercase )

        __UpperCAmelCase    :						Optional[int]       =						outputs.encoder_last_hidden_state
        __UpperCAmelCase    :						Tuple       =						outputs.last_hidden_state

        with tempfile.TemporaryDirectory() as tmpdirname:
          __UpperCAmelCase    :						Union[str, Any]       =						model.get_encoder()
          encoder.save_pretrained(__lowercase )
          __UpperCAmelCase    :						Optional[Any]       =						MaMaaaEncoder.from_pretrained(__lowercase ).to(__lowercase )

        __UpperCAmelCase    :						List[str]       =						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    :						Optional[int]       =						model.get_decoder()
          decoder.save_pretrained(__lowercase )
          __UpperCAmelCase    :						Any       =						MaMaaaDecoder.from_pretrained(__lowercase ).to(__lowercase )

        __UpperCAmelCase    :						str       =						decoder(
            input_ids=inputs_dict['''decoder_input_ids''']						,				attention_mask=inputs_dict['''decoder_attention_mask''']						,				encoder_hidden_states=__lowercase						,				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 							snake_case							(			__UpperCAmelCase      ,  __UpperCAmelCase      ,  __UpperCAmelCase      ,  unittest.TestCase ):

      '''simple docstring'''



      _A     :       Dict         =       (
          (
              MaMaaaModel,
              MaMaaaForConditionalGeneration,
          )
          if is_torch_available()
          else ()
      )
      _A     :       Tuple         =       (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
      _A     :       Tuple         =       (
          {
              'conversational': MaMaaaForConditionalGeneration,
              'feature-extraction': MaMaaaModel,
              'summarization': MaMaaaForConditionalGeneration,
              'text2text-generation': MaMaaaForConditionalGeneration,
              'translation': MaMaaaForConditionalGeneration,
          }
          if is_torch_available()
          else {}
      )
      _A     :       Union[str, Any]         =       True
      _A     :       int         =       True
      _A     :       Tuple         =       False
      _A     :       Tuple         =       False

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


        '''simple docstring'''




        __UpperCAmelCase    :						str       =						MaMaaaModelTester(self )
        __UpperCAmelCase    :						List[str]       =						ConfigTester(self						,				config_class=__lowercase )

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


        '''simple docstring'''




        self.config_tester.run_common_tests()

      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




        __UpperCAmelCase       ,     __UpperCAmelCase    :						List[Any]       =						self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
          __UpperCAmelCase    :						int       =						model_class(__lowercase )

          with tempfile.TemporaryDirectory() as tmpdirname:
            model.save_pretrained(__lowercase )
            __UpperCAmelCase       ,     __UpperCAmelCase    :						Optional[int]       =						model_class.from_pretrained(__lowercase						,				output_loading_info=__lowercase )
          self.assertEqual(info['''missing_keys''']						,				[] )

      def       A_					(							self       :      int ):


        '''simple docstring'''




        __UpperCAmelCase    :						List[Any]       =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*__lowercase )

      def       A_					(							self       :      str ):


        '''simple docstring'''




        __UpperCAmelCase    :						int       =						self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.check_encoder_decoder_model_standalone(*__lowercase )

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


        '''simple docstring'''




        __UpperCAmelCase       ,     __UpperCAmelCase    :						Tuple       =						self.model_tester.prepare_config_and_inputs_for_common()

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

          __UpperCAmelCase    :						str       =						copy.deepcopy(self._prepare_for_class(__lowercase						,				__lowercase ) )

          if not self.is_encoder_decoder:
            __UpperCAmelCase    :						str       =						inputs['''input_ids''']
            del inputs["input_ids"]
          else:
            __UpperCAmelCase    :						Union[str, Any]       =						inputs['''input_ids''']
            __UpperCAmelCase    :						Tuple       =						inputs.get('''decoder_input_ids'''						,				__lowercase )
            del inputs["input_ids"]
            inputs.pop('''decoder_input_ids'''						,				__lowercase )

          __UpperCAmelCase    :						Union[str, Any]       =						model.get_input_embeddings()
          if not self.is_encoder_decoder:
            __UpperCAmelCase    :						int       =						wte(__lowercase )
          else:
            __UpperCAmelCase    :						Union[str, Any]       =						wte(__lowercase )
            __UpperCAmelCase    :						Optional[Any]       =						wte(__lowercase )

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







      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




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


def       lowerCamelCase_       (   UpperCAmelCase_  )						->Optional[Any]:





  """simple docstring"""


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


lowercase__				:Dict				   =       1E-4







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

      '''simple docstring'''



      @cached_property
      def       A_					(							self       :      Tuple ):


        '''simple docstring'''




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

      def       A_					(							self       :      List[Any] ):


        '''simple docstring'''




        __UpperCAmelCase    :						Dict       =						MaMaaaModel.from_pretrained('''facebook/m2m100_418M''' ).to(__lowercase )
        __UpperCAmelCase    :						Dict       =						_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    :						str       =						prepare_mam_aaa_inputs_dict(model.config						,				__lowercase						,				__lowercase )
        with torch.no_grad():
          __UpperCAmelCase    :						Optional[int]       =						model(**__lowercase )[0]
        __UpperCAmelCase    :						str       =						torch.Size((1, 11, 1_024) )
        self.assertEqual(output.shape						,				__lowercase )
        # change to expected output here
        __UpperCAmelCase    :						str       =						torch.tensor(
            [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]]						,				device=__lowercase )
        self.assertTrue(torch.allclose(output[:, :3, :3]						,				__lowercase						,				atol=__lowercase ) )

      def       A_					(							self       :      Optional[int] ):


        '''simple docstring'''




        __UpperCAmelCase    :						int       =						MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M''' ).to(__lowercase )

        # change to intended input
        __UpperCAmelCase    :						Any       =						_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]] )
        __UpperCAmelCase    :						Union[str, Any]       =						_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]] )
        __UpperCAmelCase    :						Optional[Any]       =						prepare_mam_aaa_inputs_dict(model.config						,				__lowercase						,				__lowercase )
        with torch.no_grad():
          __UpperCAmelCase    :						List[Any]       =						model(**__lowercase )[0]
        __UpperCAmelCase    :						Optional[int]       =						torch.Size((1, 11, model.config.vocab_size) )
        self.assertEqual(output.shape						,				__lowercase )
        # change to expected output here
        __UpperCAmelCase    :						Union[str, Any]       =						torch.tensor(
            [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]]						,				device=__lowercase )
        self.assertTrue(torch.allclose(output[:, :3, :3]						,				__lowercase						,				atol=__lowercase ) )







      def       A_					(							self       :      int ):


        '''simple docstring'''




        __UpperCAmelCase    :						List[str]       =						MaMaaaForConditionalGeneration.from_pretrained('''facebook/m2m100_418M''' ).to(__lowercase )
        __UpperCAmelCase    :						Tuple       =						MaMaaaTokenizer.from_pretrained('''facebook/m2m100_418M'''						,				src_lang='''fr'''						,				tgt_lang='''en''' )

        __UpperCAmelCase    :						Optional[Any]       =						[
            '''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    :						Tuple       =						tokenizer(__lowercase						,				padding=__lowercase						,				return_tensors='''pt''' )

        __UpperCAmelCase    :						List[Any]       =						model.generate(
            input_ids=dct['''input_ids'''].to(__lowercase )						,				attention_mask=dct['''attention_mask'''].to(__lowercase )						,				num_beams=5						,				forced_bos_token_id=tokenizer.get_lang_id('''en''' )						,				)

        __UpperCAmelCase    :						Any       =						[
            '''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=__lowercase						,				skip_special_tokens=__lowercase )
        assert generated == expected_en






"""simple docstring"""





import argparse

import torch

from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert
from transformers.utils import logging


logging.set_verbosity_info()


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  )						->Optional[int]:





  """simple docstring"""


  __UpperCAmelCase    :						Dict       =						LxmertConfig.from_json_file(UpperCAmelCase_  )
  print(f'''Building PyTorch model from configuration: {config}'''  )
  __UpperCAmelCase    :						Tuple       =						LxmertForPreTraining(UpperCAmelCase_  )

  # Load weights from tf checkpoint
  load_tf_weights_in_lxmert(UpperCAmelCase_  ,			UpperCAmelCase_  ,			UpperCAmelCase_  )

  # Save pytorch-model
  print(f'''Save PyTorch model to {pytorch_dump_path}'''  )
  torch.save(model.state_dict()  ,			UpperCAmelCase_  )


if __name__ == "__main__":
  lowercase__				:Optional[int]				   =       argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
  )
  parser.add_argument(
      '--config_file',
      default=None,
      type=str,
      required=True,
      help='The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.',
  )
  parser.add_argument(
      '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
  )
  lowercase__				:Union[str, Any]				   =       parser.parse_args()
  convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)