

import inspect
import unittest
import warnings

from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import (
          MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
          MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
          MODEL_MAPPING,
          DeiTForImageClassification,
          DeiTForImageClassificationWithTeacher,
          DeiTForMaskedImageModeling,
          DeiTModel,
      )
      from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import DeiTImageProcessor




class   UpperCamelCase			:

    def __init__(      self			:   Optional[int]				,     snake_case__			:   Union[str, Any]				,     snake_case__			:   Optional[Any]=1_3				,     snake_case__			:   Optional[int]=3_0				,     snake_case__			:   Optional[Any]=2				,     snake_case__			:   str=3				,     snake_case__			:   Tuple=True				,     snake_case__			:   Dict=True				,     snake_case__			:   int=3_2				,     snake_case__			:   Optional[int]=5				,     snake_case__			:   List[Any]=4				,     snake_case__			:   Optional[int]=3_7				,     snake_case__			:   int="gelu"				,     snake_case__			:   int=0.1				,     snake_case__			:   Optional[int]=0.1				,     snake_case__			:   List[str]=1_0				,     snake_case__			:   Optional[Any]=0.02				,     snake_case__			:   int=3				,     snake_case__			:   List[Any]=None				,     snake_case__			:   List[Any]=2				,     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      parent
     SCREAMING_SNAKE_CASE		    =      batch_size
     SCREAMING_SNAKE_CASE		    =      image_size
     SCREAMING_SNAKE_CASE		    =      patch_size
     SCREAMING_SNAKE_CASE		    =      num_channels
     SCREAMING_SNAKE_CASE		    =      is_training
     SCREAMING_SNAKE_CASE		    =      use_labels
     SCREAMING_SNAKE_CASE		    =      hidden_size
     SCREAMING_SNAKE_CASE		    =      num_hidden_layers
     SCREAMING_SNAKE_CASE		    =      num_attention_heads
     SCREAMING_SNAKE_CASE		    =      intermediate_size
     SCREAMING_SNAKE_CASE		    =      hidden_act
     SCREAMING_SNAKE_CASE		    =      hidden_dropout_prob
     SCREAMING_SNAKE_CASE		    =      attention_probs_dropout_prob
     SCREAMING_SNAKE_CASE		    =      type_sequence_label_size
     SCREAMING_SNAKE_CASE		    =      initializer_range
     SCREAMING_SNAKE_CASE		    =      scope
     SCREAMING_SNAKE_CASE		    =      encoder_stride

     # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
     SCREAMING_SNAKE_CASE		    =      (image_size // patch_size) ** 2
     SCREAMING_SNAKE_CASE		    =      num_patches + 2

    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

     SCREAMING_SNAKE_CASE		    =      None
     if self.use_labels:
      SCREAMING_SNAKE_CASE		    =      ids_tensor([self.batch_size]				,     self.type_sequence_label_size     )

     SCREAMING_SNAKE_CASE		    =      self.get_config()

     return config, pixel_values, labels

    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     return DeiTConfig(
         image_size=self.image_size				,     patch_size=self.patch_size				,     num_channels=self.num_channels				,     hidden_size=self.hidden_size				,     num_hidden_layers=self.num_hidden_layers				,     num_attention_heads=self.num_attention_heads				,     intermediate_size=self.intermediate_size				,     hidden_act=self.hidden_act				,     hidden_dropout_prob=self.hidden_dropout_prob				,     attention_probs_dropout_prob=self.attention_probs_dropout_prob				,     is_decoder=snake_case__				,     initializer_range=self.initializer_range				,     encoder_stride=self.encoder_stride				,     )

    def UpperCamelCase      (      self			:   Optional[Any]				,     snake_case__			:   List[str]				,     snake_case__			:   Optional[Any]				,     snake_case__			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      DeiTModel(config=snake_case__     )
     model.to(snake_case__     )
     model.eval()
     SCREAMING_SNAKE_CASE		    =      model(snake_case__     )
     self.parent.assertEqual(result.last_hidden_state.shape				,     (self.batch_size, self.seq_length, self.hidden_size)     )

    def UpperCamelCase      (      self			:   int				,     snake_case__			:   Dict				,     snake_case__			:   str				,     snake_case__			:   List[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      DeiTForMaskedImageModeling(config=snake_case__     )
     model.to(snake_case__     )
     model.eval()
     SCREAMING_SNAKE_CASE		    =      model(snake_case__     )
     self.parent.assertEqual(
         result.reconstruction.shape				,     (self.batch_size, self.num_channels, self.image_size, self.image_size)     )

     # test greyscale images
     SCREAMING_SNAKE_CASE		    =      1
     SCREAMING_SNAKE_CASE		    =      DeiTForMaskedImageModeling(snake_case__     )
     model.to(snake_case__     )
     model.eval()

     SCREAMING_SNAKE_CASE		    =      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
     SCREAMING_SNAKE_CASE		    =      model(snake_case__     )
     self.parent.assertEqual(result.reconstruction.shape				,     (self.batch_size, 1, self.image_size, self.image_size)     )

    def UpperCamelCase      (      self			:   List[Any]				,     snake_case__			:   Optional[int]				,     snake_case__			:   Dict				,     snake_case__			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.type_sequence_label_size
     SCREAMING_SNAKE_CASE		    =      DeiTForImageClassification(snake_case__     )
     model.to(snake_case__     )
     model.eval()
     SCREAMING_SNAKE_CASE		    =      model(snake_case__				,     labels=snake_case__     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.type_sequence_label_size)     )

     # test greyscale images
     SCREAMING_SNAKE_CASE		    =      1
     SCREAMING_SNAKE_CASE		    =      DeiTForImageClassification(snake_case__     )
     model.to(snake_case__     )
     model.eval()

     SCREAMING_SNAKE_CASE		    =      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
     SCREAMING_SNAKE_CASE		    =      model(snake_case__				,     labels=snake_case__     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.type_sequence_label_size)     )




    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.prepare_config_and_inputs()
     (
         (
         SCREAMING_SNAKE_CASE
     )    ,						(
         SCREAMING_SNAKE_CASE
     )    ,						(
         SCREAMING_SNAKE_CASE
     )    ,						
     )		    =      config_and_inputs
     SCREAMING_SNAKE_CASE		    =      {'pixel_values': pixel_values}
     return config, inputs_dict




@require_torch
class   UpperCamelCase			(  SCREAMING_SNAKE_CASE						,      SCREAMING_SNAKE_CASE						,      unittest.TestCase ):
    __UpperCamelCase    =(
        (
            DeiTModel,
            DeiTForImageClassification,
            DeiTForImageClassificationWithTeacher,
            DeiTForMaskedImageModeling,
        )
        if is_torch_available()
        else ()
    )
    __UpperCamelCase    =(
        {
            "feature-extraction": DeiTModel,
            "image-classification": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
        }
        if is_torch_available()
        else {}
    )

    __UpperCamelCase    =False
    __UpperCamelCase    =False
    __UpperCamelCase    =False

    def UpperCamelCase      (      self			:   List[str]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      DeiTModelTester(self     )
     SCREAMING_SNAKE_CASE		    =      ConfigTester(self				,     config_class=snake_case__				,     has_text_modality=snake_case__				,     hidden_size=3_7     )

    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     self.config_tester.run_common_tests()

    @unittest.skip(reason='DeiT does not use inputs_embeds'     )
    def UpperCamelCase      (      self			:   Union[str, Any]     ):

     """simple docstring"""






     pass

    def UpperCamelCase      (      self			:   Optional[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )
      self.assertIsInstance(model.get_input_embeddings()				,     (nn.Module)     )
      SCREAMING_SNAKE_CASE		    =      model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(snake_case__				,     nn.Linear     )     )

    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )
      SCREAMING_SNAKE_CASE		    =      inspect.signature(model.forward     )
      # signature.parameters is an OrderedDict => so arg_names order is deterministic
      SCREAMING_SNAKE_CASE		    =      [*signature.parameters.keys()]

      SCREAMING_SNAKE_CASE		    =      ['pixel_values']
      self.assertListEqual(arg_names[:1]				,     snake_case__     )

    def UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*snake_case__     )

    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*snake_case__     )

    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*snake_case__     )

    def UpperCamelCase      (      self			:   str				,     snake_case__			:   int				,     snake_case__			:   Optional[Any]				,     snake_case__			:   str=False     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      super()._prepare_for_class(snake_case__				,     snake_case__				,     return_labels=snake_case__     )

     if return_labels:
      if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
       del inputs_dict["labels"]

     return inputs_dict

    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     if not self.model_tester.is_training:
      return

     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()
     SCREAMING_SNAKE_CASE		    =      True

     for model_class in self.all_model_classes:
      # DeiTForImageClassificationWithTeacher supports inference-only
      if (
          model_class in get_values(snake_case__     )
          or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
      ):
       continue
      SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )
      model.to(snake_case__     )
      model.train()
      SCREAMING_SNAKE_CASE		    =      self._prepare_for_class(snake_case__				,     snake_case__				,     return_labels=snake_case__     )
      SCREAMING_SNAKE_CASE		    =      model(**snake_case__     ).loss
      loss.backward()

    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()
     if not self.model_tester.is_training:
      return

     SCREAMING_SNAKE_CASE		    =      False
     SCREAMING_SNAKE_CASE		    =      True

     for model_class in self.all_model_classes:
      if model_class in get_values(snake_case__     ) or not model_class.supports_gradient_checkpointing:
       continue
      # DeiTForImageClassificationWithTeacher supports inference-only
      if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
       continue
      SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )
      model.gradient_checkpointing_enable()
      model.to(snake_case__     )
      model.train()
      SCREAMING_SNAKE_CASE		    =      self._prepare_for_class(snake_case__				,     snake_case__				,     return_labels=snake_case__     )
      SCREAMING_SNAKE_CASE		    =      model(**snake_case__     ).loss
      loss.backward()

    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()

     SCREAMING_SNAKE_CASE		    =      [
         {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float},
         {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long},
         {'title': 'regression', 'num_labels': 1, 'dtype': torch.float},
     ]

     for model_class in self.all_model_classes:
      if (
          model_class
          not in [
              *get_values(snake_case__     ),
              *get_values(snake_case__     ),
          ]
          or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
      ):
       continue

      for problem_type in problem_types:
       with self.subTest(msg=F"""Testing {model_class} with {problem_type['title']}"""     ):
        SCREAMING_SNAKE_CASE		    =      problem_type['title']
        SCREAMING_SNAKE_CASE		    =      problem_type['num_labels']

        SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )
        model.to(snake_case__     )
        model.train()

        SCREAMING_SNAKE_CASE		    =      self._prepare_for_class(snake_case__				,     snake_case__				,     return_labels=snake_case__     )

        if problem_type["num_labels"] > 1:
         SCREAMING_SNAKE_CASE		    =      inputs['labels'].unsqueeze(1     ).repeat(1				,     problem_type['num_labels']     )

        SCREAMING_SNAKE_CASE		    =      inputs['labels'].to(problem_type['dtype']     )

        # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
        # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
        # they have the same size." which is a symptom something in wrong for the regression problem.
        # See https://github.com/huggingface/transformers/issues/11780
        with warnings.catch_warnings(record=snake_case__     ) as warning_list:
         SCREAMING_SNAKE_CASE		    =      model(**snake_case__     ).loss
        for w in warning_list:
         if "Using a target size that is different to the input size" in str(w.message     ):
          raise ValueError(
              F"""Something is going wrong in the regression problem: intercepted {w.message}"""     )

        loss.backward()




    @slow
    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      SCREAMING_SNAKE_CASE		    =      DeiTModel.from_pretrained(snake_case__     )
      self.assertIsNotNone(snake_case__     )


def 							__lowerCAmelCase     (							)		->				str:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
 return image




@require_torch
@require_vision
class   UpperCamelCase			(  unittest.TestCase ):

    @cached_property
    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     return (
         DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224'     )
         if is_vision_available()
         else None
     )

    @slow
    def UpperCamelCase      (      self			:   Union[str, Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'     ).to(
         snake_case__     )

     SCREAMING_SNAKE_CASE		    =      self.default_image_processor
     SCREAMING_SNAKE_CASE		    =      prepare_img()
     SCREAMING_SNAKE_CASE		    =      image_processor(images=snake_case__				,     return_tensors='pt'     ).to(snake_case__     )

     # forward pass
     with torch.no_grad():
      SCREAMING_SNAKE_CASE		    =      model(**snake_case__     )

     # verify the logits
     SCREAMING_SNAKE_CASE		    =      torch.Size((1, 1_0_0_0)     )
     self.assertEqual(outputs.logits.shape				,     snake_case__     )

     SCREAMING_SNAKE_CASE		    =      torch.tensor([-1.0_266, 0.1_912, -1.2_861]     ).to(snake_case__     )

     self.assertTrue(torch.allclose(outputs.logits[0, :3]				,     snake_case__				,     atol=1E-4     )     )




    @slow
    @require_accelerate
    @require_torch_gpu
    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      DeiTModel.from_pretrained(
         'facebook/deit-base-distilled-patch16-224'				,     torch_dtype=torch.floataa				,     device_map='auto'     )
     SCREAMING_SNAKE_CASE		    =      self.default_image_processor

     SCREAMING_SNAKE_CASE		    =      prepare_img()
     SCREAMING_SNAKE_CASE		    =      image_processor(images=snake_case__				,     return_tensors='pt'     )
     SCREAMING_SNAKE_CASE		    =      inputs.pixel_values.to(snake_case__     )

     # forward pass to make sure inference works in fp16
     with torch.no_grad():
      SCREAMING_SNAKE_CASE		    =      model(snake_case__     )




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		:	int		,				_UpperCamelCase		:	Optional[Any]		,				_UpperCamelCase		:	Optional[Any]		,				_UpperCamelCase		:	Dict=None		,				_UpperCamelCase		:	Dict=None		,				_UpperCamelCase		:	int=None		,				_UpperCamelCase		:	Optional[Any]=None		,				_UpperCamelCase		:	List[Any]=None		,				)		->				Tuple:
 '''simple docstring'''


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

    def __init__(      self			:   Optional[Any]				,     snake_case__			:   List[str]				,     snake_case__			:   Any=1_3				,     snake_case__			:   List[str]=7				,     snake_case__			:   Optional[int]=True				,     snake_case__			:   Tuple=False				,     snake_case__			:   Optional[int]=9_9				,     snake_case__			:   List[str]=1_6				,     snake_case__			:   int=2				,     snake_case__			:   Optional[int]=4				,     snake_case__			:   str=4				,     snake_case__			:   Dict="relu"				,     snake_case__			:   Tuple=0.1				,     snake_case__			:   Union[str, Any]=0.1				,     snake_case__			:   Any=0.0				,     snake_case__			:   Dict=0.0				,     snake_case__			:   Optional[Any]=2_0				,     snake_case__			:   int=2				,     snake_case__			:   Optional[Any]=1				,     snake_case__			:   Any=0				,     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






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

     SCREAMING_SNAKE_CASE		    =      self.get_config()
     SCREAMING_SNAKE_CASE		    =      prepare_mam_aaa_inputs_dict(snake_case__				,     snake_case__				,     snake_case__     )
     return config, inputs_dict

    def UpperCamelCase      (      self			:   int     ):

     """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 UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   Tuple				,     snake_case__			:   List[str]				,     snake_case__			:   Dict     ):

     """simple docstring"""






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

     # first forward pass
     SCREAMING_SNAKE_CASE		    =      model(snake_case__				,     attention_mask=snake_case__				,     head_mask=snake_case__				,     use_cache=snake_case__     )

     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      outputs.to_tuple()

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

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

     SCREAMING_SNAKE_CASE		    =      model(snake_case__				,     attention_mask=snake_case__     )['last_hidden_state']
     SCREAMING_SNAKE_CASE		    =      model(snake_case__				,     attention_mask=snake_case__				,     past_key_values=snake_case__     )[
         'last_hidden_state'
     ]

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




    def UpperCamelCase      (      self			:   List[str]				,     snake_case__			:   Any				,     snake_case__			:   Dict     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      MaMaaaModel(config=snake_case__     ).to(snake_case__     ).eval()
     SCREAMING_SNAKE_CASE		    =      model(**snake_case__     )

     SCREAMING_SNAKE_CASE		    =      outputs.encoder_last_hidden_state
     SCREAMING_SNAKE_CASE		    =      outputs.last_hidden_state

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

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

     SCREAMING_SNAKE_CASE		    =      decoder(
         input_ids=inputs_dict['decoder_input_ids']				,     attention_mask=inputs_dict['decoder_attention_mask']				,     encoder_hidden_states=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   UpperCamelCase			(  SCREAMING_SNAKE_CASE						,      SCREAMING_SNAKE_CASE						,      SCREAMING_SNAKE_CASE						,      unittest.TestCase ):
    __UpperCamelCase    =(
        (
            MaMaaaModel,
            MaMaaaForConditionalGeneration,
        )
        if is_torch_available()
        else ()
    )
    __UpperCamelCase    =(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
    __UpperCamelCase    =(
        {
            "conversational": MaMaaaForConditionalGeneration,
            "feature-extraction": MaMaaaModel,
            "summarization": MaMaaaForConditionalGeneration,
            "text2text-generation": MaMaaaForConditionalGeneration,
            "translation": MaMaaaForConditionalGeneration,
        }
        if is_torch_available()
        else {}
    )
    __UpperCamelCase    =True
    __UpperCamelCase    =True
    __UpperCamelCase    =False
    __UpperCamelCase    =False

    def UpperCamelCase      (      self			:   Optional[Any]				,     snake_case__			:   Any				,     snake_case__			:   Tuple				,     snake_case__			:   List[str]				,     snake_case__			:   Optional[int]				,     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 UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      MaMaaaModelTester(self     )
     SCREAMING_SNAKE_CASE		    =      ConfigTester(self				,     config_class=snake_case__     )

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

     """simple docstring"""






     self.config_tester.run_common_tests()

    def UpperCamelCase      (      self			:   Optional[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs()
     for model_class in self.all_model_classes:
      SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )

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

    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_decoder_model_past_large_inputs(*snake_case__     )

    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_encoder_decoder_model_standalone(*snake_case__     )

    def UpperCamelCase      (      self			:   List[str]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
      SCREAMING_SNAKE_CASE		    =      model_class(snake_case__     )
      model.to(snake_case__     )
      model.eval()

      SCREAMING_SNAKE_CASE		    =      copy.deepcopy(self._prepare_for_class(snake_case__				,     snake_case__     )     )

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

      SCREAMING_SNAKE_CASE		    =      model.get_input_embeddings()
      if not self.is_encoder_decoder:
       SCREAMING_SNAKE_CASE		    =      wte(snake_case__     )
      else:
       SCREAMING_SNAKE_CASE		    =      wte(snake_case__     )
       SCREAMING_SNAKE_CASE		    =      wte(snake_case__     )

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




    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






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


def 							__lowerCAmelCase     (							_UpperCamelCase		:	Tuple						)		->				Dict:
 '''simple docstring'''


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


a_     :    Optional[int]     		=   1e-4




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

    @cached_property
    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'     )

    def UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      MaMaaaModel.from_pretrained('facebook/m2m100_418M'     ).to(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      _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]]     )
     SCREAMING_SNAKE_CASE		    =      _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]]     )
     SCREAMING_SNAKE_CASE		    =      prepare_mam_aaa_inputs_dict(model.config				,     snake_case__				,     snake_case__     )
     with torch.no_grad():
      SCREAMING_SNAKE_CASE		    =      model(**snake_case__     )[0]
     SCREAMING_SNAKE_CASE		    =      torch.Size((1, 1_1, 1_0_2_4)     )
     self.assertEqual(output.shape				,     snake_case__     )
     # change to expected output here
     SCREAMING_SNAKE_CASE		    =      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=snake_case__     )
     self.assertTrue(torch.allclose(output[:, :3, :3]				,     snake_case__				,     atol=snake_case__     )     )

    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'     ).to(snake_case__     )

     # change to intended input
     SCREAMING_SNAKE_CASE		    =      _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]]     )
     SCREAMING_SNAKE_CASE		    =      _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]]     )
     SCREAMING_SNAKE_CASE		    =      prepare_mam_aaa_inputs_dict(model.config				,     snake_case__				,     snake_case__     )
     with torch.no_grad():
      SCREAMING_SNAKE_CASE		    =      model(**snake_case__     )[0]
     SCREAMING_SNAKE_CASE		    =      torch.Size((1, 1_1, model.config.vocab_size)     )
     self.assertEqual(output.shape				,     snake_case__     )
     # change to expected output here
     SCREAMING_SNAKE_CASE		    =      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=snake_case__     )
     self.assertTrue(torch.allclose(output[:, :3, :3]				,     snake_case__				,     atol=snake_case__     )     )




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

     """simple docstring"""






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

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

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

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

     SCREAMING_SNAKE_CASE		    =      tokenizer.batch_decode(
         hypotheses_batch.tolist()				,     clean_up_tokenization_spaces=snake_case__				,     skip_special_tokens=snake_case__     )
     assert generated == expected_en

