
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


_UpperCAmelCase					: Optional[int]      =       datasets.logging.get_logger(__name__)


_UpperCAmelCase					: List[str]      =       "\\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"

_UpperCAmelCase					: List[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"

_UpperCAmelCase					: Optional[int]      =       "\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       (					lowercase    ,       lowercase    ,       lowercase=False    ,       lowercase=False    ,       lowercase=True    ,       lowercase=False    ,       lowercase="dummy_doc" )   ->  List[str]:
		'''simple docstring'''

		UpperCamelCase		=     {doc: key_lines}
		UpperCamelCase		=     {doc: sys_lines}

		UpperCamelCase		=     {}

		UpperCamelCase		=     0
		UpperCamelCase		=     0
		UpperCamelCase		=     0
		UpperCamelCase		=     0
		UpperCamelCase		=     0
		UpperCamelCase		=     0

		UpperCamelCase	,  UpperCamelCase		=     reader.get_doc_mentions(lowercase    ,       key_doc_lines[doc]    ,       lowercase )
		key_singletons_num += singletons_num

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

		UpperCamelCase	,  UpperCamelCase		=     reader.get_doc_mentions(lowercase    ,       sys_doc_lines[doc]    ,       lowercase )
		sys_singletons_num += singletons_num

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

		if remove_nested:
				UpperCamelCase	,  UpperCamelCase		=     reader.remove_nested_coref_mentions(lowercase    ,       lowercase )
				key_nested_coref_num += nested_mentions
				key_removed_nested_clusters += removed_clusters

				UpperCamelCase	,  UpperCamelCase		=     reader.remove_nested_coref_mentions(lowercase    ,       lowercase )
				sys_nested_coref_num += nested_mentions
				sys_removed_nested_clusters += removed_clusters

		UpperCamelCase		=     reader.get_mention_assignments(lowercase    ,       lowercase )
		UpperCamelCase		=     reader.get_mention_assignments(lowercase    ,       lowercase )

		UpperCamelCase		=     (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       (					lowercase    ,       lowercase    ,       lowercase    ,       lowercase    ,       lowercase    ,       lowercase    ,       lowercase )   ->  List[str]:
		'''simple docstring'''

		UpperCamelCase		=     get_coref_infos(lowercase    ,       lowercase    ,       lowercase    ,       lowercase    ,       lowercase    ,       lowercase )

		UpperCamelCase		=     {}
		UpperCamelCase		=     0
		UpperCamelCase		=     0

		for name, metric in metrics:
				UpperCamelCase	,  UpperCamelCase	,  UpperCamelCase		=     evaluator.evaluate_documents(lowercase    ,       lowercase    ,       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:
				UpperCamelCase		=     (conll / 3) * 100
				logger.info(f'''CoNLL score: {conll:.2f}''' )
				output_scores.update({'conll_score': conll} )

		return output_scores


def       A       (					lowercase )   ->  List[Any]:
		'''simple docstring'''

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


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



		def __UpperCamelCase ( self       )  ->					Optional[int]:
				"""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 __UpperCamelCase ( self				,      A_				,      A_				,      A_=True				,      A_=False				,      A_=False				,      A_=False       )  ->					List[Any]:
				"""simple docstring"""
				UpperCamelCase		=     [
				    ('mentions', evaluator.mentions),
				    ('muc', evaluator.muc),
				    ('bcub', evaluator.b_cubed),
				    ('ceafe', evaluator.ceafe),
				    ('lea', evaluator.lea),
				]

				if min_span:
						UpperCamelCase		=     util.check_gold_parse_annotation(A_       )
						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"

				UpperCamelCase		=     evaluate(
				    key_lines=A_				,      sys_lines=A_				,      metrics=A_				,      NP_only=A_				,      remove_nested=A_				,      keep_singletons=A_				,      min_span=A_				,      )

				return score


from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_UpperCAmelCase					: List[Any]      =       logging.get_logger(__name__)

_UpperCAmelCase					: Optional[Any]      =       {
    "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json",
    # See all Marian models at https://huggingface.co/models?filter=marian
}


class 				lowercase					(		_SCREAMING_SNAKE_CASE   ):
		__lowercase       :       int	     =				"marian"
		__lowercase       :       List[str]	     =				["past_key_values"]
		__lowercase       :       Any	     =				{"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}



		def __init__( self				,      A_=58_101				,      A_=None				,      A_=1_024				,      A_=12				,      A_=4_096				,      A_=16				,      A_=12				,      A_=4_096				,      A_=16				,      A_=0.0				,      A_=0.0				,      A_=True				,      A_=True				,      A_="gelu"				,      A_=1_024				,      A_=0.1				,      A_=0.0				,      A_=0.0				,      A_=0.02				,      A_=58_100				,      A_=False				,      A_=58_100				,      A_=0				,      A_=0				,      A_=True				,      **A_				,      )  ->					Optional[int]:
				"""simple docstring"""
				UpperCamelCase		=     vocab_size
				UpperCamelCase		=     decoder_vocab_size or vocab_size
				UpperCamelCase		=     max_position_embeddings
				UpperCamelCase		=     d_model
				UpperCamelCase		=     encoder_ffn_dim
				UpperCamelCase		=     encoder_layers
				UpperCamelCase		=     encoder_attention_heads
				UpperCamelCase		=     decoder_ffn_dim
				UpperCamelCase		=     decoder_layers
				UpperCamelCase		=     decoder_attention_heads
				UpperCamelCase		=     dropout
				UpperCamelCase		=     attention_dropout
				UpperCamelCase		=     activation_dropout
				UpperCamelCase		=     activation_function
				UpperCamelCase		=     init_std
				UpperCamelCase		=     encoder_layerdrop
				UpperCamelCase		=     decoder_layerdrop
				UpperCamelCase		=     use_cache
				UpperCamelCase		=     encoder_layers
				UpperCamelCase		=     scale_embedding  # scale factor will be sqrt(d_model) if True
				UpperCamelCase		=     share_encoder_decoder_embeddings
				super().__init__(
				    pad_token_id=A_				,      eos_token_id=A_				,      is_encoder_decoder=A_				,      decoder_start_token_id=A_				,      forced_eos_token_id=A_				,      **A_				,      )






class 				lowercase					(		_SCREAMING_SNAKE_CASE   ):



		@property
		# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
		def __UpperCamelCase ( self       )  ->					Mapping[str, Mapping[int, str]]:
				"""simple docstring"""
				if self.task in ["default", "seq2seq-lm"]:
						UpperCamelCase		=     OrderedDict(
						    [
						        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
						        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
						    ]       )

						if self.use_past:
								UpperCamelCase		=     {0: 'batch'}
								UpperCamelCase		=     {0: 'batch', 1: 'past_decoder_sequence + sequence'}
						else:
								UpperCamelCase		=     {0: 'batch', 1: 'decoder_sequence'}
								UpperCamelCase		=     {0: 'batch', 1: 'decoder_sequence'}

						if self.use_past:
								self.fill_with_past_key_values_(A_				,      direction='inputs'       )
				elif self.task == "causal-lm":
						# TODO: figure this case out.
						UpperCamelCase		=     OrderedDict(
						    [
						        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
						        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
						    ]       )
						if self.use_past:
								UpperCamelCase	,  UpperCamelCase		=     self.num_layers
								for i in range(A_       ):
										UpperCamelCase		=     {0: 'batch', 2: 'past_sequence + sequence'}
										UpperCamelCase		=     {0: 'batch', 2: 'past_sequence + sequence'}
				else:
						UpperCamelCase		=     OrderedDict(
						    [
						        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
						        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
						        ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
						        ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
						    ]       )

				return common_inputs



		@property
		# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
		def __UpperCamelCase ( self       )  ->					Mapping[str, Mapping[int, str]]:
				"""simple docstring"""
				if self.task in ["default", "seq2seq-lm"]:
						UpperCamelCase		=     super().outputs
				else:
						UpperCamelCase		=     super(A_				,      self       ).outputs
						if self.use_past:
								UpperCamelCase	,  UpperCamelCase		=     self.num_layers
								for i in range(A_       ):
										UpperCamelCase		=     {0: 'batch', 2: 'past_sequence + sequence'}
										UpperCamelCase		=     {0: 'batch', 2: 'past_sequence + sequence'}
				return common_outputs



		def __UpperCamelCase ( self				,      A_				,      A_ = -1				,      A_ = -1				,      A_ = False				,      A_ = None				,      )  ->					Mapping[str, Any]:
				"""simple docstring"""
				UpperCamelCase		=     self._generate_dummy_inputs_for_encoder_and_decoder(
				    A_				,      A_				,      A_				,      A_				,      A_       )

				# Generate decoder inputs
				UpperCamelCase		=     seq_length if not self.use_past else 1
				UpperCamelCase		=     self._generate_dummy_inputs_for_encoder_and_decoder(
				    A_				,      A_				,      A_				,      A_				,      A_       )
				UpperCamelCase		=     {F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
				UpperCamelCase		=     dict(**A_				,      **A_       )

				if self.use_past:
						if not is_torch_available():
								raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'       )
						else:
								import torch
						UpperCamelCase	,  UpperCamelCase		=     common_inputs['input_ids'].shape
						UpperCamelCase		=     common_inputs['decoder_input_ids'].shape[1]
						UpperCamelCase	,  UpperCamelCase		=     self.num_attention_heads
						UpperCamelCase		=     (
						    batch,
						    num_encoder_attention_heads,
						    encoder_seq_length,
						    self._config.hidden_size // num_encoder_attention_heads,
						)
						UpperCamelCase		=     decoder_seq_length + 3
						UpperCamelCase		=     (
						    batch,
						    num_decoder_attention_heads,
						    decoder_past_length,
						    self._config.hidden_size // num_decoder_attention_heads,
						)

						UpperCamelCase		=     torch.cat(
						    [common_inputs['decoder_attention_mask'], torch.ones(A_				,      A_       )]				,      dim=1       )

						UpperCamelCase		=     []
						# If the number of encoder and decoder layers are present in the model configuration, both are considered
						UpperCamelCase	,  UpperCamelCase		=     self.num_layers
						UpperCamelCase		=     min(A_				,      A_       )
						UpperCamelCase		=     max(A_				,      A_       ) - min_num_layers
						UpperCamelCase		=     'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

						for _ in range(A_       ):
								common_inputs["past_key_values"].append(
								    (
								        torch.zeros(A_       ),
								        torch.zeros(A_       ),
								        torch.zeros(A_       ),
								        torch.zeros(A_       ),
								    )       )
						# TODO: test this.
						UpperCamelCase		=     encoder_shape if remaining_side_name == 'encoder' else decoder_shape
						for _ in range(A_				,      A_       ):
								common_inputs["past_key_values"].append((torch.zeros(A_       ), torch.zeros(A_       ))       )
				return common_inputs



		def __UpperCamelCase ( self				,      A_				,      A_ = -1				,      A_ = -1				,      A_ = False				,      A_ = None				,      )  ->					Mapping[str, Any]:
				"""simple docstring"""
				UpperCamelCase		=     self._generate_dummy_inputs_for_encoder_and_decoder(
				    A_				,      A_				,      A_				,      A_				,      A_       )

				if self.use_past:
						if not is_torch_available():
								raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'       )
						else:
								import torch
						UpperCamelCase	,  UpperCamelCase		=     common_inputs['input_ids'].shape
						# Not using the same length for past_key_values
						UpperCamelCase		=     seqlen + 2
						UpperCamelCase	,  UpperCamelCase		=     self.num_layers
						UpperCamelCase	,  UpperCamelCase		=     self.num_attention_heads
						UpperCamelCase		=     (
						    batch,
						    num_encoder_attention_heads,
						    past_key_values_length,
						    self._config.hidden_size // num_encoder_attention_heads,
						)

						UpperCamelCase		=     common_inputs['attention_mask'].dtype
						UpperCamelCase		=     torch.cat(
						    [common_inputs['attention_mask'], torch.ones(A_				,      A_				,      dtype=A_       )]				,      dim=1       )
						UpperCamelCase		=     [
						    (torch.zeros(A_       ), torch.zeros(A_       )) for _ in range(A_       )
						]
				return common_inputs



		def __UpperCamelCase ( self				,      A_				,      A_ = -1				,      A_ = -1				,      A_ = False				,      A_ = None				,      )  ->					Mapping[str, Any]:
				"""simple docstring"""
				# Copied from OnnxConfig.generate_dummy_inputs
				# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
				# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
				UpperCamelCase		=     compute_effective_axis_dimension(
				    A_				,      fixed_dimension=OnnxConfig.default_fixed_batch				,      num_token_to_add=0       )

				# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
				UpperCamelCase		=     tokenizer.num_special_tokens_to_add(A_       )
				UpperCamelCase		=     compute_effective_axis_dimension(
				    A_				,      fixed_dimension=OnnxConfig.default_fixed_sequence				,      num_token_to_add=A_       )

				# Generate dummy inputs according to compute batch and sequence
				UpperCamelCase		=     [' '.join([tokenizer.unk_token]       ) * seq_length] * batch_size
				UpperCamelCase		=     dict(tokenizer(A_				,      return_tensors=A_       )       )
				return common_inputs



		def __UpperCamelCase ( self				,      A_				,      A_ = -1				,      A_ = -1				,      A_ = False				,      A_ = None				,      )  ->					Mapping[str, Any]:
				"""simple docstring"""
				if self.task in ["default", "seq2seq-lm"]:
						UpperCamelCase		=     self._generate_dummy_inputs_for_default_and_seqaseq_lm(
						    A_				,      batch_size=A_				,      seq_length=A_				,      is_pair=A_				,      framework=A_       )

				else:
						UpperCamelCase		=     self._generate_dummy_inputs_for_causal_lm(
						    A_				,      batch_size=A_				,      seq_length=A_				,      is_pair=A_				,      framework=A_       )

				return common_inputs



		def __UpperCamelCase ( self				,      A_				,      A_				,      A_				,      A_       )  ->					int:
				"""simple docstring"""
				if self.task in ["default", "seq2seq-lm"]:
						UpperCamelCase		=     super()._flatten_past_key_values_(A_				,      A_				,      A_				,      A_       )
				else:
						UpperCamelCase		=     super(A_				,      self       )._flatten_past_key_values_(
						    A_				,      A_				,      A_				,      A_       )



		@property
		def __UpperCamelCase ( self       )  ->					float:
				"""simple docstring"""
				return 1e-4
