






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


__magic_name__:  Optional[Any]  	=			logging.get_logger(__name__)

__magic_name__:  int  	=			{
    "google/bigbird-pegasus-large-arxiv": (
        "https://huggingface.co/google/bigbird-pegasus-large-arxiv/resolve/main/config.json"
    ),
    "google/bigbird-pegasus-large-pubmed": (
        "https://huggingface.co/google/bigbird-pegasus-large-pubmed/resolve/main/config.json"
    ),
    "google/bigbird-pegasus-large-bigpatent": (
        "https://huggingface.co/google/bigbird-pegasus-large-bigpatent/resolve/main/config.json"
    ),
    # See all BigBirdPegasus models at https://huggingface.co/models?filter=bigbird_pegasus
}





class  snake_case__      (							_lowerCAmelCase   ):
	lowercase__		:  List[str]							   =					'''bigbird_pegasus'''
	lowercase__		:  Any							   =					['''past_key_values''']
	lowercase__		:  Optional[Any]							   =					{
	    '''num_attention_heads''': '''encoder_attention_heads''',
	    '''hidden_size''': '''d_model''',
	    '''attention_probs_dropout_prob''': '''attention_dropout''',
	}
	def __init__(       self    ,     lowerCAmelCase__=9_61_03    ,     lowerCAmelCase__=40_96    ,     lowerCAmelCase__=16    ,     lowerCAmelCase__=40_96    ,     lowerCAmelCase__=16    ,     lowerCAmelCase__=16    ,     lowerCAmelCase__=40_96    ,     lowerCAmelCase__=16    ,     lowerCAmelCase__=0.0    ,     lowerCAmelCase__=0.0    ,     lowerCAmelCase__=True    ,     lowerCAmelCase__=True    ,     lowerCAmelCase__="gelu_new"    ,     lowerCAmelCase__=10_24    ,     lowerCAmelCase__=0.1    ,     lowerCAmelCase__=0.0    ,     lowerCAmelCase__=0.0    ,     lowerCAmelCase__=0.0_2    ,     lowerCAmelCase__=2    ,     lowerCAmelCase__=0.0    ,     lowerCAmelCase__=True    ,     lowerCAmelCase__=0    ,     lowerCAmelCase__=2    ,     lowerCAmelCase__=1    ,     lowerCAmelCase__="block_sparse"    ,     lowerCAmelCase__=64    ,     lowerCAmelCase__=3    ,     lowerCAmelCase__=False    ,     **lowerCAmelCase__    ,     )							->   Optional[Any]:
							__magic_name__    :     List[str]     		=      vocab_size
							__magic_name__    :     str     		=      max_position_embeddings
							__magic_name__    :     str     		=      d_model
							__magic_name__    :     str     		=      encoder_ffn_dim
							__magic_name__    :     Union[str, Any]     		=      encoder_layers
							__magic_name__    :     Optional[Any]     		=      encoder_attention_heads
							__magic_name__    :     Optional[Any]     		=      decoder_ffn_dim
							__magic_name__    :     Any     		=      decoder_layers
							__magic_name__    :     List[str]     		=      decoder_attention_heads
							__magic_name__    :     Union[str, Any]     		=      dropout
							__magic_name__    :     Optional[Any]     		=      attention_dropout
							__magic_name__    :     Union[str, Any]     		=      activation_dropout
							__magic_name__    :     int     		=      activation_function
							__magic_name__    :     Tuple     		=      init_std
							__magic_name__    :     Tuple     		=      encoder_layerdrop
							__magic_name__    :     Optional[Any]     		=      decoder_layerdrop
							__magic_name__    :     Optional[Any]     		=      classifier_dropout
							__magic_name__    :     Dict     		=      use_cache
							__magic_name__    :     Optional[int]     		=      encoder_layers
							__magic_name__    :     Optional[int]     		=      scale_embedding  # scale factor will be sqrt(d_model) if True

							# extra config
							__magic_name__    :     Optional[int]     		=      attention_type
							__magic_name__    :     Dict     		=      block_size
							__magic_name__    :     Any     		=      num_random_blocks
							__magic_name__    :     Dict     		=      use_bias

							super().__init__(
							    pad_token_id=lowerCAmelCase__    ,     bos_token_id=lowerCAmelCase__    ,     eos_token_id=lowerCAmelCase__    ,     is_encoder_decoder=lowerCAmelCase__    ,     decoder_start_token_id=lowerCAmelCase__    ,     **lowerCAmelCase__    ,     )





class  snake_case__      (							_lowerCAmelCase   ):
	@property
	def     __magic_name__       (       self				)							->   Mapping[str, Mapping[int, str]]:
							if self.task in ["default", "seq2seq-lm"]:
													__magic_name__    :     Optional[Any]     		=      OrderedDict(
													    [
													        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
													        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
													    ]				)

													if self.use_past:
																			__magic_name__    :     str     		=      {0: """batch"""}
																			__magic_name__    :     str     		=      {0: """batch""", 1: """past_decoder_sequence + sequence"""}
													else:
																			__magic_name__    :     List[Any]     		=      {0: """batch""", 1: """decoder_sequence"""}
																			__magic_name__    :     str     		=      {0: """batch""", 1: """decoder_sequence"""}

													if self.use_past:
																			self.fill_with_past_key_values_(lowerCAmelCase__    ,     direction="""inputs"""				)
							elif self.task == "causal-lm":
													# TODO: figure this case out.
													__magic_name__    :     Union[str, Any]     		=      OrderedDict(
													    [
													        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
													        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
													    ]				)
													if self.use_past:
																			__magic_name__		,__magic_name__    :     Tuple     		=      self.num_layers
																			for i in range(lowerCAmelCase__				):
																									__magic_name__    :     Dict     		=      {0: """batch""", 2: """past_sequence + sequence"""}
																									__magic_name__    :     Tuple     		=      {0: """batch""", 2: """past_sequence + sequence"""}
							else:
													__magic_name__    :     str     		=      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
	def     __magic_name__       (       self				)							->   Mapping[str, Mapping[int, str]]:
							if self.task in ["default", "seq2seq-lm"]:
													__magic_name__    :     int     		=      super().outputs
							else:
													__magic_name__    :     Optional[int]     		=      super(lowerCAmelCase__    ,     self				).outputs
													if self.use_past:
																			__magic_name__		,__magic_name__    :     str     		=      self.num_layers
																			for i in range(lowerCAmelCase__				):
																									__magic_name__    :     Tuple     		=      {0: """batch""", 2: """past_sequence + sequence"""}
																									__magic_name__    :     List[str]     		=      {0: """batch""", 2: """past_sequence + sequence"""}
							return common_outputs
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = False    ,     lowerCAmelCase__ = None    ,     )							->   Mapping[str, Any]:
							__magic_name__    :     Any     		=      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)

							# Generate decoder inputs
							__magic_name__    :     Optional[int]     		=      seq_length if not self.use_past else 1
							__magic_name__    :     List[str]     		=      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)
							__magic_name__    :     List[Any]     		=      {F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
							__magic_name__    :     List[Any]     		=      dict(**lowerCAmelCase__    ,     **lowerCAmelCase__				)

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

													__magic_name__    :     List[str]     		=      torch.cat(
													    [common_inputs["""decoder_attention_mask"""], torch.ones(lowerCAmelCase__    ,     lowerCAmelCase__				)]    ,     dim=1				)

													__magic_name__    :     Optional[int]     		=      []
													# If the number of encoder and decoder layers are present in the model configuration, both are considered
													__magic_name__		,__magic_name__    :     Tuple     		=      self.num_layers
													__magic_name__    :     Dict     		=      min(lowerCAmelCase__    ,     lowerCAmelCase__				)
													__magic_name__    :     int     		=      max(lowerCAmelCase__    ,     lowerCAmelCase__				) - min_num_layers
													__magic_name__    :     Tuple     		=      """encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

													for _ in range(lowerCAmelCase__				):
																			common_inputs["past_key_values"].append(
																			    (
																			        torch.zeros(lowerCAmelCase__				),
																			        torch.zeros(lowerCAmelCase__				),
																			        torch.zeros(lowerCAmelCase__				),
																			        torch.zeros(lowerCAmelCase__				),
																			    )				)
													# TODO: test this.
													__magic_name__    :     int     		=      encoder_shape if remaining_side_name == """encoder""" else decoder_shape
													for _ in range(lowerCAmelCase__    ,     lowerCAmelCase__				):
																			common_inputs["past_key_values"].append((torch.zeros(lowerCAmelCase__				), torch.zeros(lowerCAmelCase__				))				)
							return common_inputs
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = False    ,     lowerCAmelCase__ = None    ,     )							->   Mapping[str, Any]:
							__magic_name__    :     Union[str, Any]     		=      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)

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

													__magic_name__    :     List[str]     		=      common_inputs["""attention_mask"""].dtype
													__magic_name__    :     Optional[Any]     		=      torch.cat(
													    [common_inputs["""attention_mask"""], torch.ones(lowerCAmelCase__    ,     lowerCAmelCase__    ,     dtype=lowerCAmelCase__				)]    ,     dim=1				)
													__magic_name__    :     Dict     		=      [
													    (torch.zeros(lowerCAmelCase__				), torch.zeros(lowerCAmelCase__				)) for _ in range(lowerCAmelCase__				)
													]
							return common_inputs
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = False    ,     lowerCAmelCase__ = None    ,     )							->   Mapping[str, Any]:
							# 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
							__magic_name__    :     List[str]     		=      compute_effective_axis_dimension(
							    lowerCAmelCase__    ,     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
							__magic_name__    :     Optional[Any]     		=      tokenizer.num_special_tokens_to_add(lowerCAmelCase__				)
							__magic_name__    :     Dict     		=      compute_effective_axis_dimension(
							    lowerCAmelCase__    ,     fixed_dimension=OnnxConfig.default_fixed_sequence    ,     num_token_to_add=lowerCAmelCase__				)

							# Generate dummy inputs according to compute batch and sequence
							__magic_name__    :     Optional[int]     		=      [""" """.join([tokenizer.unk_token]				) * seq_length] * batch_size
							__magic_name__    :     int     		=      dict(tokenizer(lowerCAmelCase__    ,     return_tensors=lowerCAmelCase__				)				)
							return common_inputs
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = -1    ,     lowerCAmelCase__ = False    ,     lowerCAmelCase__ = None    ,     )							->   Mapping[str, Any]:
							if self.task in ["default", "seq2seq-lm"]:
													__magic_name__    :     Tuple     		=      self._generate_dummy_inputs_for_default_and_seqaseq_lm(
													    lowerCAmelCase__    ,     batch_size=lowerCAmelCase__    ,     seq_length=lowerCAmelCase__    ,     is_pair=lowerCAmelCase__    ,     framework=lowerCAmelCase__				)

							elif self.task == "causal-lm":
													__magic_name__    :     Dict     		=      self._generate_dummy_inputs_for_causal_lm(
													    lowerCAmelCase__    ,     batch_size=lowerCAmelCase__    ,     seq_length=lowerCAmelCase__    ,     is_pair=lowerCAmelCase__    ,     framework=lowerCAmelCase__				)
							else:
													__magic_name__    :     List[Any]     		=      self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    lowerCAmelCase__    ,     batch_size=lowerCAmelCase__    ,     seq_length=lowerCAmelCase__    ,     is_pair=lowerCAmelCase__    ,     framework=lowerCAmelCase__				)

							return common_inputs







	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   Optional[int]:
							if self.task in ["default", "seq2seq-lm"]:
													__magic_name__    :     List[str]     		=      super()._flatten_past_key_values_(lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)
							else:
													__magic_name__    :     str     		=      super(lowerCAmelCase__    ,     self				)._flatten_past_key_values_(
													    lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)








import sacrebleu as scb
from packaging import version

import datasets


__magic_name__:  Optional[int]  	=			"\\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

__magic_name__:  int  	=			"\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n"

__magic_name__:  List[Any]  	=			"\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `'exp'`. Possible values are:\n        - `'none'`: no smoothing\n        - `'floor'`: increment zero counts\n        - `'add-k'`: increment num/denom by k for n>1\n        - `'exp'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method='floor'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method='add-k'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `'zh'` for Chinese, `'ja-mecab'` for Japanese and `'13a'` (mteval) otherwise. Possible values are:\n        - `'none'`: No tokenization.\n        - `'zh'`: Chinese tokenization.\n        - `'13a'`: mimics the `mteval-v13a` script from Moses.\n        - `'intl'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `'char'`: Language-agnostic character-level tokenization.\n        - `'ja-mecab'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    'score': BLEU score,\n    'counts': Counts,\n    'totals': Totals,\n    'precisions': Precisions,\n    'bp': Brevity penalty,\n    'sys_len': predictions length,\n    'ref_len': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = [\"hello there general kenobi\", \"foo bar foobar\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"], [\"foo bar foobar\", \"foo bar foobar\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = [\"hello there general kenobi\",\n        ...                 \"on our way to ankh morpork\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"],\n        ...                 [\"goodbye ankh morpork\", \"ankh morpork\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        39.8\n"





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,						_KWARGS_DESCRIPTION   )
class  snake_case__      (							datasets.Metric   ):
	def     __magic_name__       (       self				)							->   Optional[int]:
							if version.parse(scb.__version__				) < version.parse("""1.4.12"""				):
													raise ImportWarning(
													    """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
													    """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""				)
							return datasets.MetricInfo(
							    description=_DESCRIPTION    ,     citation=_CITATION    ,     homepage="""https://github.com/mjpost/sacreBLEU"""    ,     inputs_description=_KWARGS_DESCRIPTION    ,     features=datasets.Features(
							        {
							            """predictions""": datasets.Value("""string"""    ,     id="""sequence"""				),
							            """references""": datasets.Sequence(datasets.Value("""string"""    ,     id="""sequence"""				)    ,     id="""references"""				),
							        }				)    ,     codebase_urls=["""https://github.com/mjpost/sacreBLEU"""]    ,     reference_urls=[
							        """https://github.com/mjpost/sacreBLEU""",
							        """https://en.wikipedia.org/wiki/BLEU""",
							        """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""",
							    ]    ,     )







	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__="exp"    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     lowerCAmelCase__=False    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     )							->   Optional[Any]:
							__magic_name__    :     Optional[int]     		=      len(references[0]				)
							if any(len(lowerCAmelCase__				) != references_per_prediction for refs in references				):
													raise ValueError("""Sacrebleu requires the same number of references for each prediction"""				)
							__magic_name__    :     Dict     		=      [[refs[i] for refs in references] for i in range(lowerCAmelCase__				)]
							__magic_name__    :     List[str]     		=      scb.corpus_bleu(
							    lowerCAmelCase__    ,     lowerCAmelCase__    ,     smooth_method=lowerCAmelCase__    ,     smooth_value=lowerCAmelCase__    ,     force=lowerCAmelCase__    ,     lowercase=lowerCAmelCase__    ,     use_effective_order=lowerCAmelCase__    ,     **({"""tokenize""": tokenize} if tokenize else {})    ,     )
							__magic_name__    :     List[str]     		=      {
							    """score""": output.score,
							    """counts""": output.counts,
							    """totals""": output.totals,
							    """precisions""": output.precisions,
							    """bp""": output.bp,
							    """sys_len""": output.sys_len,
							    """ref_len""": output.ref_len,
							}
							return output_dict
