






'''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 					lowercase__				(   __UpperCamelCase	,		__UpperCamelCase	,		__UpperCamelCase	,		__UpperCamelCase=None	,		__UpperCamelCase=None	,		__UpperCamelCase=None	,		__UpperCamelCase=None	,		__UpperCamelCase=None	,		)->				Optional[Any]:
      if attention_mask is None:
            UpperCamelCase       						=      input_ids.ne(config.pad_token_id					)
      if decoder_attention_mask is None:
            UpperCamelCase       						=      decoder_input_ids.ne(config.pad_token_id					)
      if head_mask is None:
            UpperCamelCase       						=      torch.ones(config.encoder_layers	,		config.encoder_attention_heads	,		device=__UpperCamelCase					)
      if decoder_head_mask is None:
            UpperCamelCase       						=      torch.ones(config.decoder_layers	,		config.decoder_attention_heads	,		device=__UpperCamelCase					)
      if cross_attn_head_mask is None:
            UpperCamelCase       						=      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    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE=13    ,	_SCREAMING_SNAKE_CASE=7    ,	_SCREAMING_SNAKE_CASE=True    ,	_SCREAMING_SNAKE_CASE=False    ,	_SCREAMING_SNAKE_CASE=99    ,	_SCREAMING_SNAKE_CASE=16    ,	_SCREAMING_SNAKE_CASE=2    ,	_SCREAMING_SNAKE_CASE=4    ,	_SCREAMING_SNAKE_CASE=4    ,	_SCREAMING_SNAKE_CASE="relu"    ,	_SCREAMING_SNAKE_CASE=0.1    ,	_SCREAMING_SNAKE_CASE=0.1    ,	_SCREAMING_SNAKE_CASE=0.0    ,	_SCREAMING_SNAKE_CASE=0.0    ,	_SCREAMING_SNAKE_CASE=20    ,	_SCREAMING_SNAKE_CASE=2    ,	_SCREAMING_SNAKE_CASE=1    ,	_SCREAMING_SNAKE_CASE=0    ,	)						->   List[Any]:



        """simple docstring"""






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

  def 						A__		(   self   )						->   Dict:



        """simple docstring"""






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

        UpperCamelCase       						=      self.get_config()
        UpperCamelCase       						=      prepare_mam_aaa_inputs_dict(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )
        return config, inputs_dict

  def 						A__		(   self   )						->   Union[str, 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   )						->   Any:



        """simple docstring"""






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

  def 						A__		(   self    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )						->   int:



        """simple docstring"""






        UpperCamelCase       						=      MaMaaaModel(config=_SCREAMING_SNAKE_CASE   ).get_decoder().to(_SCREAMING_SNAKE_CASE   ).eval()
        UpperCamelCase       						=      inputs_dict["""input_ids"""]
        UpperCamelCase       						=      inputs_dict["""attention_mask"""]
        UpperCamelCase       						=      inputs_dict["""head_mask"""]

        # first forward pass
        UpperCamelCase       						=      model(_SCREAMING_SNAKE_CASE    ,	attention_mask=_SCREAMING_SNAKE_CASE    ,	head_mask=_SCREAMING_SNAKE_CASE    ,	use_cache=_SCREAMING_SNAKE_CASE   )

        UpperCamelCase						,UpperCamelCase       						=      outputs.to_tuple()

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

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

        UpperCamelCase       						=      model(_SCREAMING_SNAKE_CASE    ,	attention_mask=_SCREAMING_SNAKE_CASE   )["""last_hidden_state"""]
        UpperCamelCase       						=      model(_SCREAMING_SNAKE_CASE    ,	attention_mask=_SCREAMING_SNAKE_CASE    ,	past_key_values=_SCREAMING_SNAKE_CASE   )[
            """last_hidden_state"""
        ]

        # select random slice
        UpperCamelCase       						=      ids_tensor((1,)    ,	output_from_past.shape[-1]   ).item()
        UpperCamelCase       						=      output_from_no_past[:, -3:, random_slice_idx].detach()
        UpperCamelCase       						=      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 						A__		(   self    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )						->   Optional[int]:



        """simple docstring"""






        UpperCamelCase       						=      MaMaaaModel(config=_SCREAMING_SNAKE_CASE   ).to(_SCREAMING_SNAKE_CASE   ).eval()
        UpperCamelCase       						=      model(**_SCREAMING_SNAKE_CASE   )

        UpperCamelCase       						=      outputs.encoder_last_hidden_state
        UpperCamelCase       						=      outputs.last_hidden_state

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

        UpperCamelCase       						=      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       						=      model.get_decoder()
              decoder.save_pretrained(_SCREAMING_SNAKE_CASE   )
              UpperCamelCase       						=      MaMaaaDecoder.from_pretrained(_SCREAMING_SNAKE_CASE   ).to(_SCREAMING_SNAKE_CASE   )

        UpperCamelCase       						=      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_		(    lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, unittest.TestCase       ):
  lowercase  	=   (
      (
          MaMaaaModel,
          MaMaaaForConditionalGeneration,
      )
      if is_torch_available()
      else ()
  )
  lowercase  	=   (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
  lowercase  	=   (
      {
          """conversational""": MaMaaaForConditionalGeneration,
          """feature-extraction""": MaMaaaModel,
          """summarization""": MaMaaaForConditionalGeneration,
          """text2text-generation""": MaMaaaForConditionalGeneration,
          """translation""": MaMaaaForConditionalGeneration,
      }
      if is_torch_available()
      else {}
  )
  lowercase  	=   True
  lowercase  	=   True
  lowercase  	=   False
  lowercase  	=   False

  def 						A__		(   self    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )						->   Union[str, 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   )						->   Optional[int]:



        """simple docstring"""






        UpperCamelCase       						=      MaMaaaModelTester(self   )
        UpperCamelCase       						=      ConfigTester(self    ,	config_class=_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   Optional[Any]:



        """simple docstring"""






        self.config_tester.run_common_tests()

  def 						A__		(   self   )						->   Dict:



        """simple docstring"""






        UpperCamelCase						,UpperCamelCase       						=      self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
              UpperCamelCase       						=      model_class(_SCREAMING_SNAKE_CASE   )

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

  def 						A__		(   self   )						->   Optional[int]:



        """simple docstring"""






        UpperCamelCase       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   Dict:



        """simple docstring"""






        UpperCamelCase       						=      self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.check_encoder_decoder_model_standalone(*_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   Dict:



        """simple docstring"""






        UpperCamelCase						,UpperCamelCase       						=      self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
              UpperCamelCase       						=      model_class(_SCREAMING_SNAKE_CASE   )
              model.to(_SCREAMING_SNAKE_CASE   )
              model.eval()

              UpperCamelCase       						=      copy.deepcopy(self._prepare_for_class(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )   )

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

              UpperCamelCase       						=      model.get_input_embeddings()
              if not self.is_encoder_decoder:
                    UpperCamelCase       						=      wte(_SCREAMING_SNAKE_CASE   )
              else:
                    UpperCamelCase       						=      wte(_SCREAMING_SNAKE_CASE   )
                    UpperCamelCase       						=      wte(_SCREAMING_SNAKE_CASE   )

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


  def 						A__		(   self   )						->   int:



        """simple docstring"""






        UpperCamelCase						,UpperCamelCase       						=      self.model_tester.prepare_config_and_inputs()
        UpperCamelCase       						=      input_dict["""input_ids"""]
        UpperCamelCase       						=      input_ids.ne(1   ).to(_SCREAMING_SNAKE_CASE   )
        UpperCamelCase       						=      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 					lowercase__				(   __UpperCamelCase					)->				Any:
      return torch.tensor(__UpperCamelCase	,		dtype=torch.long	,		device=__UpperCamelCase					)


SCREAMING_SNAKE_CASE__											=     1E-4






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

  @cached_property
  def 						A__		(   self   )						->   Any:



        """simple docstring"""






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

  def 						A__		(   self   )						->   str:



        """simple docstring"""






        UpperCamelCase       						=      MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""   ).to(_SCREAMING_SNAKE_CASE   )
        UpperCamelCase       						=      _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]   )
        UpperCamelCase       						=      _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]   )
        UpperCamelCase       						=      prepare_mam_aaa_inputs_dict(model.config    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )
        with torch.no_grad():
              UpperCamelCase       						=      model(**_SCREAMING_SNAKE_CASE   )[0]
        UpperCamelCase       						=      torch.Size((1, 11, 1024)   )
        self.assertEqual(output.shape    ,	_SCREAMING_SNAKE_CASE   )
        # change to expected output here
        UpperCamelCase       						=      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=_SCREAMING_SNAKE_CASE   )
        self.assertTrue(torch.allclose(output[:, :3, :3]    ,	_SCREAMING_SNAKE_CASE    ,	atol=_SCREAMING_SNAKE_CASE   )   )

  def 						A__		(   self   )						->   Tuple:



        """simple docstring"""






        UpperCamelCase       						=      MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""   ).to(_SCREAMING_SNAKE_CASE   )

        # change to intended input
        UpperCamelCase       						=      _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]   )
        UpperCamelCase       						=      _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]   )
        UpperCamelCase       						=      prepare_mam_aaa_inputs_dict(model.config    ,	_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )
        with torch.no_grad():
              UpperCamelCase       						=      model(**_SCREAMING_SNAKE_CASE   )[0]
        UpperCamelCase       						=      torch.Size((1, 11, model.config.vocab_size)   )
        self.assertEqual(output.shape    ,	_SCREAMING_SNAKE_CASE   )
        # change to expected output here
        UpperCamelCase       						=      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=_SCREAMING_SNAKE_CASE   )
        self.assertTrue(torch.allclose(output[:, :3, :3]    ,	_SCREAMING_SNAKE_CASE    ,	atol=_SCREAMING_SNAKE_CASE   )   )


  def 						A__		(   self   )						->   List[Any]:



        """simple docstring"""






        UpperCamelCase       						=      MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""   ).to(_SCREAMING_SNAKE_CASE   )
        UpperCamelCase       						=      MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""    ,	src_lang="""fr"""    ,	tgt_lang="""en"""   )

        UpperCamelCase       						=      [
            """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       						=      tokenizer(_SCREAMING_SNAKE_CASE    ,	padding=_SCREAMING_SNAKE_CASE    ,	return_tensors="""pt"""   )

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

        UpperCamelCase       						=      [
            """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       						=      tokenizer.batch_decode(
            hypotheses_batch.tolist()    ,	clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE    ,	skip_special_tokens=_SCREAMING_SNAKE_CASE   )
        assert generated == expected_en








'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import _LazyModule


SCREAMING_SNAKE_CASE__											=     {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']}


if TYPE_CHECKING:
     from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer
else:
     import sys

     SCREAMING_SNAKE_CASE__											=     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
