

import collections
from typing import List, Optional, Union

from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer


A__						=							logging.get_logger(__name__)

A__						=							{"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

A__						=							{
    "vocab_file": {
        "facebook/dpr-ctx_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt"
        ),
        "facebook/dpr-ctx_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "facebook/dpr-ctx_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json"
        ),
        "facebook/dpr-ctx_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json"
        ),
    },
}
A__						=							{
    "vocab_file": {
        "facebook/dpr-question_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt"
        ),
        "facebook/dpr-question_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "facebook/dpr-question_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json"
        ),
        "facebook/dpr-question_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json"
        ),
    },
}
A__						=							{
    "vocab_file": {
        "facebook/dpr-reader-single-nq-base": (
            "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt"
        ),
        "facebook/dpr-reader-multiset-base": (
            "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "facebook/dpr-reader-single-nq-base": (
            "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json"
        ),
        "facebook/dpr-reader-multiset-base": (
            "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json"
        ),
    },
}

A__						=							{
    "facebook/dpr-ctx_encoder-single-nq-base": 512,
    "facebook/dpr-ctx_encoder-multiset-base": 512,
}
A__						=							{
    "facebook/dpr-question_encoder-single-nq-base": 512,
    "facebook/dpr-question_encoder-multiset-base": 512,
}
A__						=							{
    "facebook/dpr-reader-single-nq-base": 512,
    "facebook/dpr-reader-multiset-base": 512,
}


A__						=							{
    "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True},
    "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True},
}
A__						=							{
    "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True},
    "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True},
}
A__						=							{
    "facebook/dpr-reader-single-nq-base": {"do_lower_case": True},
    "facebook/dpr-reader-multiset-base": {"do_lower_case": True},
}

class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE			):
	_lowercase  :   str       				=  VOCAB_FILES_NAMES
	_lowercase  :   int       				=  CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
	_lowercase  :   Optional[Any]       				=  CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_lowercase  :   List[Any]       				=  CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION




class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE			):
	_lowercase  :   List[str]       				=  VOCAB_FILES_NAMES
	_lowercase  :   Dict       				=  QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
	_lowercase  :   Tuple       				=  QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_lowercase  :   Optional[Any]       				=  QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION




A__						=							collections.namedtuple(
    "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
)

A__						=							collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])


A__						=							r"\n    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n    with the format:\n\n    ```\n    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n    ```\n\n    Args:\n        questions (`str` or `List[str]`):\n            The questions to be encoded. You can specify one question for many passages. In this case, the question\n            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n            `titles` or `texts`.\n        titles (`str` or `List[str]`):\n            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n        texts (`str` or `List[str]`):\n            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n            Activates and controls padding. Accepts the following values:\n\n            - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n              if provided).\n            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided.\n            - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n              lengths).\n        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n            Activates and controls truncation. Accepts the following values:\n\n            - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n              the maximum acceptable input length for the model if that argument is not provided. This will truncate\n              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n              of pairs) is provided.\n            - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the first\n              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the\n              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n              greater than the model maximum admissible input size).\n        max_length (`int`, *optional*):\n                Controls the maximum length to use by one of the truncation/padding parameters.\n\n                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n                is required by one of the truncation/padding parameters. If the model has no specific maximum input\n                length (like XLNet) truncation/padding to a maximum length will be deactivated.\n        return_tensors (`str` or [`~utils.TensorType`], *optional*):\n                If set, will return tensors instead of list of python integers. Acceptable values are:\n\n                - `'tf'`: Return TensorFlow `tf.constant` objects.\n                - `'pt'`: Return PyTorch `torch.Tensor` objects.\n                - `'np'`: Return Numpy `np.ndarray` objects.\n        return_attention_mask (`bool`, *optional*):\n            Whether or not to return the attention mask. If not set, will return the attention mask according to the\n            specific tokenizer's default, defined by the `return_outputs` attribute.\n\n            [What are attention masks?](../glossary#attention-mask)\n\n    Returns:\n        `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n        - `input_ids`: List of token ids to be fed to a model.\n        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n    "

@add_start_docstrings(SCREAMING_SNAKE_CASE			)
class 				__UpperCamelCase				:







	def __call__(   self: Tuple  , __UpperCamelCase: Any  , __UpperCamelCase: Optional[str] = None  , __UpperCamelCase: Optional[str] = None  , __UpperCamelCase: Union[bool, str] = False  , __UpperCamelCase: Union[bool, str] = False  , __UpperCamelCase: Optional[int] = None  , __UpperCamelCase: Optional[Union[str, TensorType]] = None  , __UpperCamelCase: Optional[bool] = None  , **__UpperCamelCase: Dict  , ):

						'''simple docstring'''





						if titles is None and texts is None:
											return super().__call__(
											    __UpperCamelCase  , padding=__UpperCamelCase  , truncation=__UpperCamelCase  , max_length=__UpperCamelCase  , return_tensors=__UpperCamelCase  , return_attention_mask=__UpperCamelCase  , **__UpperCamelCase  , )
						elif titles is None or texts is None:
											__magic_name__							=    titles if texts is None else texts
											return super().__call__(
											    __UpperCamelCase  , __UpperCamelCase  , padding=__UpperCamelCase  , truncation=__UpperCamelCase  , max_length=__UpperCamelCase  , return_tensors=__UpperCamelCase  , return_attention_mask=__UpperCamelCase  , **__UpperCamelCase  , )
						__magic_name__							=    titles if not isinstance(__UpperCamelCase  , __UpperCamelCase      ) else [titles]
						__magic_name__							=    texts if not isinstance(__UpperCamelCase  , __UpperCamelCase      ) else [texts]
						__magic_name__							=    len(__UpperCamelCase      )
						__magic_name__							=    questions if not isinstance(__UpperCamelCase  , __UpperCamelCase      ) else [questions] * n_passages
						if len(__UpperCamelCase      ) != len(__UpperCamelCase      ):
											raise ValueError(
											    F'There should be as many titles than texts but got {len(__UpperCamelCase      )} titles and {len(__UpperCamelCase      )} texts.'      )
						__magic_name__							=    super().__call__(__UpperCamelCase  , __UpperCamelCase  , padding=__UpperCamelCase  , truncation=__UpperCamelCase      )['input_ids']
						__magic_name__							=    super().__call__(__UpperCamelCase  , add_special_tokens=__UpperCamelCase  , padding=__UpperCamelCase  , truncation=__UpperCamelCase      )['input_ids']
						__magic_name__							=    {
						    'input_ids': [
						        (encoded_question_and_title + encoded_text)[:max_length]
						        if max_length is not None and truncation
						        else encoded_question_and_title + encoded_text
						        for encoded_question_and_title, encoded_text in zip(__UpperCamelCase  , __UpperCamelCase      )
						    ]
						}
						if return_attention_mask is not False:
											__magic_name__							=    []
											for input_ids in encoded_inputs["input_ids"]:
																attention_mask.append([int(input_id != self.pad_token_id      ) for input_id in input_ids]      )
											__magic_name__							=    attention_mask
						return self.pad(__UpperCamelCase  , padding=__UpperCamelCase  , max_length=__UpperCamelCase  , return_tensors=__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Optional[Any]  , __UpperCamelCase: BatchEncoding  , __UpperCamelCase: DPRReaderOutput  , __UpperCamelCase: int = 16  , __UpperCamelCase: int = 64  , __UpperCamelCase: int = 4  , ):

						'''simple docstring'''





						__magic_name__							=    reader_input['input_ids']
						__magic_name__,	__magic_name__,	__magic_name__							=    reader_output[:3]
						__magic_name__							=    len(__UpperCamelCase      )
						__magic_name__							=    sorted(range(__UpperCamelCase      )  , reverse=__UpperCamelCase  , key=relevance_logits.__getitem__      )
						__magic_name__							=    []
						for doc_id in sorted_docs:
											__magic_name__							=    list(input_ids[doc_id]      )
											# assuming question & title information is at the beginning of the sequence
											__magic_name__							=    sequence_ids.index(self.sep_token_id  , 2      ) + 1  # second sep id
											if sequence_ids[-1] == self.pad_token_id:
																__magic_name__							=    sequence_ids.index(self.pad_token_id      )
											else:
																__magic_name__							=    len(__UpperCamelCase      )

											__magic_name__							=    self._get_best_spans(
											    start_logits=start_logits[doc_id][passage_offset:sequence_len]  , end_logits=end_logits[doc_id][passage_offset:sequence_len]  , max_answer_length=__UpperCamelCase  , top_spans=__UpperCamelCase  , )
											for start_index, end_index in best_spans:
																start_index += passage_offset
																end_index += passage_offset
																nbest_spans_predictions.append(
																    DPRSpanPrediction(
																        span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index]  , relevance_score=relevance_logits[doc_id]  , doc_id=__UpperCamelCase  , start_index=__UpperCamelCase  , end_index=__UpperCamelCase  , text=self.decode(sequence_ids[start_index : end_index + 1]      )  , )      )
											if len(__UpperCamelCase      ) >= num_spans:
																break
						return nbest_spans_predictions[:num_spans]







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]  , __UpperCamelCase: List[int]  , __UpperCamelCase: List[int]  , __UpperCamelCase: int  , __UpperCamelCase: int  , ):

						'''simple docstring'''





						__magic_name__							=    []
						for start_index, start_score in enumerate(__UpperCamelCase      ):
											for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]      ):
																scores.append(((start_index, start_index + answer_length), start_score + end_score)      )
						__magic_name__							=    sorted(__UpperCamelCase  , key=lambda __UpperCamelCase      : x[1]  , reverse=__UpperCamelCase      )
						__magic_name__							=    []
						for (start_index, end_index), score in scores:
											if start_index > end_index:
																raise ValueError(F'Wrong span indices: [{start_index}:{end_index}]'      )
											__magic_name__							=    end_index - start_index + 1
											if length > max_answer_length:
																raise ValueError(F'Span is too long: {length} > {max_answer_length}'      )
											if any(
											    start_index <= prev_start_index <= prev_end_index <= end_index
											    or prev_start_index <= start_index <= end_index <= prev_end_index
											    for (prev_start_index, prev_end_index) in chosen_span_intervals      ):
																continue
											chosen_span_intervals.append((start_index, end_index)      )

											if len(__UpperCamelCase      ) == top_spans:
																break
						return chosen_span_intervals




@add_end_docstrings(SCREAMING_SNAKE_CASE			)
class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE			):
	_lowercase  :   str       				=  VOCAB_FILES_NAMES
	_lowercase  :   Tuple       				=  READER_PRETRAINED_VOCAB_FILES_MAP
	_lowercase  :   Dict       				=  READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_lowercase  :   List[str]       				=  READER_PRETRAINED_INIT_CONFIGURATION
	_lowercase  :   str       				=  ["input_ids", "attention_mask"]







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     (				a_				:					Optional[Any]					,a_				:					Dict					,a_				:					Any					,a_				:					Any=None					,a_				:					Any=None					,a_				:					List[str]=None					,a_				:					Union[str, Any]=None					,a_				:					Dict=None					,)				->	Optional[Any]:




					'''simple docstring'''







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

						'''simple docstring'''





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







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict      ):

						'''simple docstring'''





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

						__magic_name__							=    self.get_config()
						__magic_name__							=    prepare_mam_aaa_inputs_dict(__UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase      )
						return config, inputs_dict







	def 	_SCREAMING_SNAKE_CASE							(   self: Optional[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 	_SCREAMING_SNAKE_CASE							(   self: Optional[Any]      ):

						'''simple docstring'''





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







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple  , __UpperCamelCase: Tuple  , __UpperCamelCase: Union[str, Any]      ):

						'''simple docstring'''





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

						# first forward pass
						__magic_name__							=    model(__UpperCamelCase  , attention_mask=__UpperCamelCase  , head_mask=__UpperCamelCase  , use_cache=__UpperCamelCase      )

						__magic_name__,	__magic_name__							=    outputs.to_tuple()

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

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

						__magic_name__							=    model(__UpperCamelCase  , attention_mask=__UpperCamelCase      )['last_hidden_state']
						__magic_name__							=    model(__UpperCamelCase  , attention_mask=__UpperCamelCase  , past_key_values=__UpperCamelCase      )[
						    'last_hidden_state'
						]

						# select random slice
						__magic_name__							=    ids_tensor((1,)  , output_from_past.shape[-1]      ).item()
						__magic_name__							=    output_from_no_past[:, -3:, random_slice_idx].detach()
						__magic_name__							=    output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]      )

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(__UpperCamelCase  , __UpperCamelCase  , atol=1E-2      )      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Union[str, Any]  , __UpperCamelCase: Any  , __UpperCamelCase: int      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModel(config=__UpperCamelCase      ).to(__UpperCamelCase      ).eval()
						__magic_name__							=    model(**__UpperCamelCase      )

						__magic_name__							=    outputs.encoder_last_hidden_state
						__magic_name__							=    outputs.last_hidden_state

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

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

						__magic_name__							=    decoder(
						    input_ids=inputs_dict['decoder_input_ids']  , attention_mask=inputs_dict['decoder_attention_mask']  , encoder_hidden_states=__UpperCamelCase  , encoder_attention_mask=inputs_dict['attention_mask']  , )[0]

						self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3      )




@require_torch
class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						unittest.TestCase			):
	_lowercase  :   Tuple       				=  (
	    (
	        MaMaaaModel,
	        MaMaaaForConditionalGeneration,
	    )
	    if is_torch_available()
	    else ()
	)
	_lowercase  :   Dict       				=  (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
	_lowercase  :   Tuple       				=  (
	    {
	        "conversational": MaMaaaForConditionalGeneration,
	        "feature-extraction": MaMaaaModel,
	        "summarization": MaMaaaForConditionalGeneration,
	        "text2text-generation": MaMaaaForConditionalGeneration,
	        "translation": MaMaaaForConditionalGeneration,
	    }
	    if is_torch_available()
	    else {}
	)
	_lowercase  :   List[str]       				=  True
	_lowercase  :   Dict       				=  True
	_lowercase  :   Union[str, Any]       				=  False
	_lowercase  :   List[Any]       				=  False







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict  , __UpperCamelCase: Any  , __UpperCamelCase: Optional[Any]  , __UpperCamelCase: List[str]  , __UpperCamelCase: Optional[Any]  , __UpperCamelCase: Tuple      ):

						'''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 	_SCREAMING_SNAKE_CASE							(   self: Tuple      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModelTester(self      )
						__magic_name__							=    ConfigTester(self  , config_class=__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						self.config_tester.run_common_tests()







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__,	__magic_name__							=    self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
											__magic_name__							=    model_class(__UpperCamelCase      )

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







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__							=    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past_large_inputs(*__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__							=    self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[str]      ):

						'''simple docstring'''





						__magic_name__,	__magic_name__							=    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
											__magic_name__							=    model_class(__UpperCamelCase      )
											model.to(__UpperCamelCase      )
											model.eval()

											__magic_name__							=    copy.deepcopy(self._prepare_for_class(__UpperCamelCase  , __UpperCamelCase      )      )

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

											__magic_name__							=    model.get_input_embeddings()
											if not self.is_encoder_decoder:
																__magic_name__							=    wte(__UpperCamelCase      )
											else:
																__magic_name__							=    wte(__UpperCamelCase      )
																__magic_name__							=    wte(__UpperCamelCase      )

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







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

						'''simple docstring'''





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




def 					_lowercase     (				a_				:					List[Any]				)				->	Union[str, Any]:




					'''simple docstring'''







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


A__						=							1e-4


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







	@cached_property
	def 	_SCREAMING_SNAKE_CASE							(   self: Any      ):

						'''simple docstring'''





						return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'      )







	def 	_SCREAMING_SNAKE_CASE							(   self: int      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModel.from_pretrained('facebook/m2m100_418M'      ).to(__UpperCamelCase      )
						__magic_name__							=    _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]      )
						__magic_name__							=    _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]      )
						__magic_name__							=    prepare_mam_aaa_inputs_dict(model.config  , __UpperCamelCase  , __UpperCamelCase      )
						with torch.no_grad():
											__magic_name__							=    model(**__UpperCamelCase      )[0]
						__magic_name__							=    torch.Size((1, 11, 10_24)      )
						self.assertEqual(output.shape  , __UpperCamelCase      )
						# change to expected output here
						__magic_name__							=    torch.tensor(
						    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]  , device=__UpperCamelCase      )
						self.assertTrue(torch.allclose(output[:, :3, :3]  , __UpperCamelCase  , atol=__UpperCamelCase      )      )







	def 	_SCREAMING_SNAKE_CASE							(   self: str      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'      ).to(__UpperCamelCase      )

						# change to intended input
						__magic_name__							=    _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]      )
						__magic_name__							=    _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]      )
						__magic_name__							=    prepare_mam_aaa_inputs_dict(model.config  , __UpperCamelCase  , __UpperCamelCase      )
						with torch.no_grad():
											__magic_name__							=    model(**__UpperCamelCase      )[0]
						__magic_name__							=    torch.Size((1, 11, model.config.vocab_size)      )
						self.assertEqual(output.shape  , __UpperCamelCase      )
						# change to expected output here
						__magic_name__							=    torch.tensor(
						    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]  , device=__UpperCamelCase      )
						self.assertTrue(torch.allclose(output[:, :3, :3]  , __UpperCamelCase  , atol=__UpperCamelCase      )      )







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

						'''simple docstring'''





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

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

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

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

						__magic_name__							=    tokenizer.batch_decode(
						    hypotheses_batch.tolist()  , clean_up_tokenization_spaces=__UpperCamelCase  , skip_special_tokens=__UpperCamelCase      )
						assert generated == expected_en




