


"""simple docstring"""
import coval  # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401
from coval.conll import reader, util
from coval.eval import evaluator

import datasets


__SCREAMING_SNAKE_CASE							:      Dict						=      datasets.logging.get_logger(__name__)


__SCREAMING_SNAKE_CASE							:      Any						=      '\\n@InProceedings{moosavi2019minimum,\n    author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n    title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n    year = {2019},\n    booktitle = {Proceedings of the 57th Annual Meeting of\n        the Association for Computational Linguistics (Volume 1: Long Papers)},\n    publisher = {Association for Computational Linguistics},\n    address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n    author = {Amit Bagga and Breck Baldwin},\n    title = {Algorithms for Scoring Coreference Chains},\n    booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n    year = {1998},\n    pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n    author = {Xiaoqiang Luo},\n    title = {On coreference resolution performance metrics},\n    booktitle = {In Proc. of HLT/EMNLP},\n    year = {2005},\n    pages = {25--32},\n    publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n    title = "Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric",\n    author = "Moosavi, Nafise Sadat  and\n      Strube, Michael",\n    booktitle = "Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",\n    month = aug,\n    year = "2016",\n    address = "Berlin, Germany",\n    publisher = "Association for Computational Linguistics",\n    url = "https://www.aclweb.org/anthology/P16-1060",\n    doi = "10.18653/v1/P16-1060",\n    pages = "632--642",\n}\n\n'

__SCREAMING_SNAKE_CASE							:      Any						=      '\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn	Type	Description\n1	Document ID	This is a variation on the document filename\n2	Part number	Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3	Word number\n4	Word itself	This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5	Part-of-Speech\n6	Parse bit	This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the "([pos] [word])" string (or leaf) and concatenating the items in the rows of that column.\n7	Predicate lemma	The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a "-"\n8	Predicate Frameset ID	This is the PropBank frameset ID of the predicate in Column 7.\n9	Word sense	This is the word sense of the word in Column 3.\n10	Speaker/Author	This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11	Named Entities	These columns identifies the spans representing various named entities.\n12:N	Predicate Arguments	There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN	Coreference	Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section "*_conll File Format"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n'

__SCREAMING_SNAKE_CASE							:      Dict						=      '\nCalculates coreference evaluation metrics.\nArgs:\n    predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n        Each prediction is a word with its annotations as a string made of columns joined with spaces.\n        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n        See the details on the format in the description of the metric.\n    references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n        Each reference is a word with its annotations as a string made of columns joined with spaces.\n        Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n        See the details on the format in the description of the metric.\n    keep_singletons: After extracting all mentions of key or system files,\n        mentions whose corresponding coreference chain is of size one,\n        are considered as singletons. The default evaluation mode will include\n        singletons in evaluations if they are included in the key or the system files.\n        By setting \'keep_singletons=False\', all singletons in the key and system files\n        will be excluded from the evaluation.\n    NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n        leave out the resolution of VPs. By setting the \'NP_only\' option, the scorer will only evaluate the resolution of NPs.\n    min_span: By setting \'min_span\', the scorer reports the results based on automatically detected minimum spans.\n        Minimum spans are determined using the MINA algorithm.\n\nReturns:\n    \'mentions\': mentions\n    \'muc\': MUC metric [Vilain et al, 1995]\n    \'bcub\': B-cubed [Bagga and Baldwin, 1998]\n    \'ceafe\': CEAFe [Luo et al., 2005]\n    \'lea\': LEA [Moosavi and Strube, 2016]\n    \'conll_score\': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n    >>> coval = datasets.load_metric(\'coval\')\n    >>> words = [\'bc/cctv/00/cctv_0005   0   0       Thank   VBP  (TOP(S(VP*    thank  01   1    Xu_li  *           (V*)        *       -\',\n    ... \'bc/cctv/00/cctv_0005   0   1         you   PRP        (NP*)      -    -   -    Xu_li  *        (ARG1*)   (ARG0*)   (116)\',\n    ... \'bc/cctv/00/cctv_0005   0   2    everyone    NN        (NP*)      -    -   -    Xu_li  *    (ARGM-DIS*)        *    (116)\',\n    ... \'bc/cctv/00/cctv_0005   0   3         for    IN        (PP*       -    -   -    Xu_li  *        (ARG2*         *       -\',\n    ... \'bc/cctv/00/cctv_0005   0   4    watching   VBG   (S(VP*))))   watch  01   1    Xu_li  *             *)      (V*)      -\',\n    ... \'bc/cctv/00/cctv_0005   0   5           .     .          *))      -    -   -    Xu_li  *             *         *       -\']\n    >>> references = [words]\n    >>> predictions = [words]\n    >>> results = coval.compute(predictions=predictions, references=references)\n    >>> print(results) # doctest:+ELLIPSIS\n    {\'mentions/recall\': 1.0,[...] \'conll_score\': 100.0}\n'







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=False			,	_SCREAMING_SNAKE_CASE=False			,	_SCREAMING_SNAKE_CASE=True			,	_SCREAMING_SNAKE_CASE=False			,	_SCREAMING_SNAKE_CASE="dummy_doc"			)      ->			Tuple:
							snake_case_          =						{doc: key_lines}
							snake_case_          =						{doc: sys_lines}

							snake_case_          =						{}

							snake_case_          =						0
							snake_case_          =						0
							snake_case_          =						0
							snake_case_          =						0
							snake_case_          =						0
							snake_case_          =						0

							snake_case_    ,  snake_case_          =						reader.get_doc_mentions(_SCREAMING_SNAKE_CASE			,	key_doc_lines[doc]			,	_SCREAMING_SNAKE_CASE			)
							key_singletons_num += singletons_num

							if NP_only or min_span:
														snake_case_          =						reader.set_annotated_parse_trees(_SCREAMING_SNAKE_CASE			,	key_doc_lines[doc]			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)

							snake_case_    ,  snake_case_          =						reader.get_doc_mentions(_SCREAMING_SNAKE_CASE			,	sys_doc_lines[doc]			,	_SCREAMING_SNAKE_CASE			)
							sys_singletons_num += singletons_num

							if NP_only or min_span:
														snake_case_          =						reader.set_annotated_parse_trees(_SCREAMING_SNAKE_CASE			,	key_doc_lines[doc]			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)

							if remove_nested:
														snake_case_    ,  snake_case_          =						reader.remove_nested_coref_mentions(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)
														key_nested_coref_num += nested_mentions
														key_removed_nested_clusters += removed_clusters

														snake_case_    ,  snake_case_          =						reader.remove_nested_coref_mentions(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)
														sys_nested_coref_num += nested_mentions
														sys_removed_nested_clusters += removed_clusters

							snake_case_          =						reader.get_mention_assignments(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)
							snake_case_          =						reader.get_mention_assignments(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)

							snake_case_          =						(key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster)

							if remove_nested:
														logger.info(
														    """Number of removed nested coreferring mentions in the key """
														    f"""annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}"""			)
														logger.info(
														    """Number of resulting singleton clusters in the key """
														    f"""annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}"""			)

							if not keep_singletons:
														logger.info(
														    f"""{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system """
														    """files, respectively"""			)

							return doc_coref_infos







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)      ->			Union[str, Any]:
							snake_case_          =						get_coref_infos(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)

							snake_case_          =						{}
							snake_case_          =						0
							snake_case_          =						0

							for name, metric in metrics:
														snake_case_    ,  snake_case_    ,  snake_case_          =						evaluator.evaluate_documents(_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	beta=1			)
														if name in ["muc", "bcub", "ceafe"]:
																					conll += fa
																					conll_subparts_num += 1
														output_scores.update({f"""{name}/recall""": recall, f"""{name}/precision""": precision, f"""{name}/f1""": fa}			)

														logger.info(
														    name.ljust(10			)			,	f"""Recall: {recall * 100:.2f}"""			,	f""" Precision: {precision * 100:.2f}"""			,	f""" F1: {fa * 100:.2f}"""			,	)

							if conll_subparts_num == 3:
														snake_case_          =						(conll / 3) * 100
														logger.info(f"""CoNLL score: {conll:.2f}"""			)
														output_scores.update({"""conll_score""": conll}			)

							return output_scores







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			str:
							snake_case_          =						False
							for line in key_lines:
														if not line.startswith("""#"""			):
																					if len(line.split()			) > 6:
																												snake_case_          =						line.split()[5]
																												if not parse_col == "-":
																																			snake_case_          =						True
																																			break
																												else:
																																			break
							return has_gold_parse





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,						_KWARGS_DESCRIPTION)
class        __A       (datasets.Metric):





							'''simple docstring'''

							def 						lowerCAmelCase    (			self							: List[str]    ):



														"""simple docstring"""



														return datasets.MetricInfo(
														    description=_DESCRIPTION						,    citation=_CITATION						,    inputs_description=_KWARGS_DESCRIPTION						,    features=datasets.Features(
														        {
														            """predictions""": datasets.Sequence(datasets.Value("""string"""    )    ),
														            """references""": datasets.Sequence(datasets.Value("""string"""    )    ),
														        }    )						,    codebase_urls=["""https://github.com/ns-moosavi/coval"""]						,    reference_urls=[
														        """https://github.com/ns-moosavi/coval""",
														        """https://www.aclweb.org/anthology/P16-1060""",
														        """http://www.conll.cemantix.org/2012/data.html""",
														    ]						,    )



							def 						lowerCAmelCase    (			self							: str						,    UpperCAmelCase_							: Tuple						,    UpperCAmelCase_							: Optional[int]						,    UpperCAmelCase_							: int=True						,    UpperCAmelCase_							: List[str]=False						,    UpperCAmelCase_							: Any=False						,    UpperCAmelCase_							: int=False    ):



														"""simple docstring"""



														snake_case_          =						[
														    ("""mentions""", evaluator.mentions),
														    ("""muc""", evaluator.muc),
														    ("""bcub""", evaluator.b_cubed),
														    ("""ceafe""", evaluator.ceafe),
														    ("""lea""", evaluator.lea),
														]

														if min_span:
																					snake_case_          =						util.check_gold_parse_annotation(UpperCAmelCase_    )
																					if not has_gold_parse:
																												raise NotImplementedError("""References should have gold parse annotation to use 'min_span'."""    )
																												# util.parse_key_file(key_file)
																												# key_file = key_file + ".parsed"

														snake_case_          =						evaluate(
														    key_lines=UpperCAmelCase_						,    sys_lines=UpperCAmelCase_						,    metrics=UpperCAmelCase_						,    NP_only=UpperCAmelCase_						,    remove_nested=UpperCAmelCase_						,    keep_singletons=UpperCAmelCase_						,    min_span=UpperCAmelCase_						,    )

														return score







"""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   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	_SCREAMING_SNAKE_CASE=None			,	)      ->			Optional[Any]:
							if attention_mask is None:
														snake_case_          =						input_ids.ne(config.pad_token_id			)
							if decoder_attention_mask is None:
														snake_case_          =						decoder_input_ids.ne(config.pad_token_id			)
							if head_mask is None:
														snake_case_          =						torch.ones(config.encoder_layers			,	config.encoder_attention_heads			,	device=_SCREAMING_SNAKE_CASE			)
							if decoder_head_mask is None:
														snake_case_          =						torch.ones(config.decoder_layers			,	config.decoder_attention_heads			,	device=_SCREAMING_SNAKE_CASE			)
							if cross_attn_head_mask is None:
														snake_case_          =						torch.ones(config.decoder_layers			,	config.decoder_attention_heads			,	device=_SCREAMING_SNAKE_CASE			)
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}





class        __A       :





							'''simple docstring'''

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



														"""simple docstring"""



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



							def 						lowerCAmelCase    (			self							: Tuple    )   ->List[str]:



														"""simple docstring"""



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

														snake_case_          =						self.get_config()
														snake_case_          =						prepare_mam_aaa_inputs_dict(UpperCAmelCase_						,    UpperCAmelCase_						,    UpperCAmelCase_    )
														return config, inputs_dict



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



														"""simple docstring"""



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



							def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Optional[Any]						,    UpperCAmelCase_							: Dict    )   ->Dict:



														"""simple docstring"""



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

														# first forward pass
														snake_case_          =						model(UpperCAmelCase_						,    attention_mask=UpperCAmelCase_						,    head_mask=UpperCAmelCase_						,    use_cache=UpperCAmelCase_    )

														snake_case_    ,  snake_case_          =						outputs.to_tuple()

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

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

														snake_case_          =						model(UpperCAmelCase_						,    attention_mask=UpperCAmelCase_    )["""last_hidden_state"""]
														snake_case_          =						model(UpperCAmelCase_						,    attention_mask=UpperCAmelCase_						,    past_key_values=UpperCAmelCase_    )[
														    """last_hidden_state"""
														]

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



							def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Union[str, Any]						,    UpperCAmelCase_							: Dict    )   ->int:



														"""simple docstring"""



														snake_case_          =						MaMaaaModel(config=UpperCAmelCase_    ).to(UpperCAmelCase_    ).eval()
														snake_case_          =						model(**UpperCAmelCase_    )

														snake_case_          =						outputs.encoder_last_hidden_state
														snake_case_          =						outputs.last_hidden_state

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

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

														snake_case_          =						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        __A       (snake_case__  ,						snake_case__  ,						snake_case__  ,						unittest.TestCase):





							'''simple docstring'''

							__lowercase:						Optional[Any]							 =      (
							    (
							        MaMaaaModel,
							        MaMaaaForConditionalGeneration,
							    )
							    if is_torch_available()
							    else ()
							)
							__lowercase:						Union[str, Any]							 =      (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:						Dict							 =      True
							__lowercase:						List[Any]							 =      True
							__lowercase:						Union[str, Any]							 =      False
							__lowercase:						Optional[int]							 =      False



							def 						lowerCAmelCase    (			self							: Union[str, Any]						,    UpperCAmelCase_							: List[str]						,    UpperCAmelCase_							: int						,    UpperCAmelCase_							: Optional[int]						,    UpperCAmelCase_							: Optional[int]						,    UpperCAmelCase_							: int    )   ->str:



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



														"""simple docstring"""



														snake_case_          =						MaMaaaModelTester(self    )
														snake_case_          =						ConfigTester(self						,    config_class=UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: Optional[Any]    )   ->Tuple:



														"""simple docstring"""



														self.config_tester.run_common_tests()



							def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->Optional[Any]:



														"""simple docstring"""



														snake_case_    ,  snake_case_          =						self.model_tester.prepare_config_and_inputs()
														for model_class in self.all_model_classes:
																					snake_case_          =						model_class(UpperCAmelCase_    )

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



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: str    )   ->List[str]:



														"""simple docstring"""



														snake_case_          =						self.model_tester.prepare_config_and_inputs_for_common()
														self.model_tester.check_encoder_decoder_model_standalone(*UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: str    )   ->List[str]:



														"""simple docstring"""



														snake_case_    ,  snake_case_          =						self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																					snake_case_          =						model_class(UpperCAmelCase_    )
																					model.to(UpperCAmelCase_    )
																					model.eval()

																					snake_case_          =						copy.deepcopy(self._prepare_for_class(UpperCAmelCase_						,    UpperCAmelCase_    )    )

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

																					snake_case_          =						model.get_input_embeddings()
																					if not self.is_encoder_decoder:
																												snake_case_          =						wte(UpperCAmelCase_    )
																					else:
																												snake_case_          =						wte(UpperCAmelCase_    )
																												snake_case_          =						wte(UpperCAmelCase_    )

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



							def 						lowerCAmelCase    (			self							: Any    )   ->Any:



														"""simple docstring"""



														snake_case_    ,  snake_case_          =						self.model_tester.prepare_config_and_inputs()
														snake_case_          =						input_dict["""input_ids"""]
														snake_case_          =						input_ids.ne(1    ).to(UpperCAmelCase_    )
														snake_case_          =						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   _a			( _SCREAMING_SNAKE_CASE			)      ->			Optional[int]:
							return torch.tensor(_SCREAMING_SNAKE_CASE			,	dtype=torch.long			,	device=_SCREAMING_SNAKE_CASE			)


__SCREAMING_SNAKE_CASE							:      Tuple						=      1E-4





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





							'''simple docstring'''

							@cached_property
							def 						lowerCAmelCase    (			self							: Dict    )   ->str:



														"""simple docstring"""



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



							def 						lowerCAmelCase    (			self							: str    )   ->Any:



														"""simple docstring"""



														snake_case_          =						MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""    ).to(UpperCAmelCase_    )
														snake_case_          =						_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]    )
														snake_case_          =						_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]    )
														snake_case_          =						prepare_mam_aaa_inputs_dict(model.config						,    UpperCAmelCase_						,    UpperCAmelCase_    )
														with torch.no_grad():
																					snake_case_          =						model(**UpperCAmelCase_    )[0]
														snake_case_          =						torch.Size((1, 11, 1_024)    )
														self.assertEqual(output.shape						,    UpperCAmelCase_    )
														# change to expected output here
														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=UpperCAmelCase_    )
														self.assertTrue(torch.allclose(output[:, :3, :3]						,    UpperCAmelCase_						,    atol=UpperCAmelCase_    )    )



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->Any:



														"""simple docstring"""



														snake_case_          =						MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""    ).to(UpperCAmelCase_    )

														# change to intended input
														snake_case_          =						_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]    )
														snake_case_          =						_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]    )
														snake_case_          =						prepare_mam_aaa_inputs_dict(model.config						,    UpperCAmelCase_						,    UpperCAmelCase_    )
														with torch.no_grad():
																					snake_case_          =						model(**UpperCAmelCase_    )[0]
														snake_case_          =						torch.Size((1, 11, model.config.vocab_size)    )
														self.assertEqual(output.shape						,    UpperCAmelCase_    )
														# change to expected output here
														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=UpperCAmelCase_    )
														self.assertTrue(torch.allclose(output[:, :3, :3]						,    UpperCAmelCase_						,    atol=UpperCAmelCase_    )    )



							def 						lowerCAmelCase    (			self							: Dict    )   ->str:



														"""simple docstring"""



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

														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
														snake_case_          =						tokenizer(UpperCAmelCase_						,    padding=UpperCAmelCase_						,    return_tensors="""pt"""    )

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

														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.""",
														]

														snake_case_          =						tokenizer.batch_decode(
														    hypotheses_batch.tolist()						,    clean_up_tokenization_spaces=UpperCAmelCase_						,    skip_special_tokens=UpperCAmelCase_    )
														assert generated == expected_en



