



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

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


_snake_case	=						logging.get_logger(__name__)

_snake_case	=						{
    "EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json",
    # See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}



class 						UpperCAmelCase_					( a):
							lowerCamelCase__         =	'gptj'
							lowerCamelCase__         =	{
							    'max_position_embeddings': 'n_positions',
							    'hidden_size': 'n_embd',
							    'num_attention_heads': 'n_head',
							    'num_hidden_layers': 'n_layer',
							}







							def __init__(     self,    __a=5_0400,    __a=2048,    __a=4096,    __a=28,    __a=16,    __a=64,    __a=None,    __a="gelu_new",    __a=0.0,    __a=0.0,    __a=0.0,    __a=1E-5,    __a=0.02,    __a=True,    __a=5_0256,    __a=5_0256,    __a=False,    **__a,    ):

														'''simple docstring'''

														_lowerCAmelCase  :							Union[str, Any]				     =					vocab_size
														_lowerCAmelCase  :							Union[str, Any]				     =					n_positions
														_lowerCAmelCase  :							str				     =					n_embd
														_lowerCAmelCase  :							Dict				     =					n_layer
														_lowerCAmelCase  :							List[Any]				     =					n_head
														_lowerCAmelCase  :							List[str]				     =					n_inner
														_lowerCAmelCase  :							Union[str, Any]				     =					rotary_dim
														_lowerCAmelCase  :							List[Any]				     =					activation_function
														_lowerCAmelCase  :							Dict				     =					resid_pdrop
														_lowerCAmelCase  :							Union[str, Any]				     =					embd_pdrop
														_lowerCAmelCase  :							str				     =					attn_pdrop
														_lowerCAmelCase  :							Optional[Any]				     =					layer_norm_epsilon
														_lowerCAmelCase  :							Union[str, Any]				     =					initializer_range
														_lowerCAmelCase  :							Union[str, Any]				     =					use_cache

														_lowerCAmelCase  :							Any				     =					bos_token_id
														_lowerCAmelCase  :							int				     =					eos_token_id

														super().__init__(
														    bos_token_id=__a,    eos_token_id=__a,    tie_word_embeddings=__a,    **__a)



class 						UpperCAmelCase_					( a):







							def __init__(     self,    __a,    __a = "default",    __a = None,    __a = False,    ):

														'''simple docstring'''

														super().__init__(__a,    task=__a,    patching_specs=__a,    use_past=__a)
														if not getattr(self._config,    "pad_token_id",    __a):
																					# TODO: how to do that better?
																					_lowerCAmelCase  :							Dict				     =					0







							@property
							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Union[str, Any]				     =					OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
														if self.use_past:
																					self.fill_with_past_key_values_(__a,    direction="inputs")
																					_lowerCAmelCase  :							Dict				     =					{0: "batch", 1: "past_sequence + sequence"}
														else:
																					_lowerCAmelCase  :							Any				     =					{0: "batch", 1: "sequence"}

														return common_inputs







							@property
							def      snake_case__   (     self):

														'''simple docstring'''

														return self._config.n_layer







							@property
							def      snake_case__   (     self):

														'''simple docstring'''

														return self._config.n_head







							def      snake_case__   (     self,    __a,    __a = -1,    __a = -1,    __a = False,    __a = None,    ):

														'''simple docstring'''

														_lowerCAmelCase  :							Union[str, Any]				     =					super(__a,    self).generate_dummy_inputs(
														    __a,    batch_size=__a,    seq_length=__a,    is_pair=__a,    framework=__a)

														# We need to order the input in the way they appears in the forward()
														_lowerCAmelCase  :							Tuple				     =					OrderedDict({"input_ids": common_inputs["input_ids"]})

														# Need to add the past_keys
														if self.use_past:
																					if not is_torch_available():
																												raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
																					else:
																												import torch

																												_lowerCAmelCase     ,					_lowerCAmelCase  :							Any				     =					common_inputs["input_ids"].shape
																												# Not using the same length for past_key_values
																												_lowerCAmelCase  :							Tuple				     =					seqlen + 2
																												_lowerCAmelCase  :							Tuple				     =					(
																												    batch,
																												    self.num_attention_heads,
																												    past_key_values_length,
																												    self._config.hidden_size // self.num_attention_heads,
																												)
																												_lowerCAmelCase  :							Optional[Any]				     =					[
																												    (torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
																												]

														_lowerCAmelCase  :							Dict				     =					common_inputs["attention_mask"]
														if self.use_past:
																					_lowerCAmelCase  :							Optional[int]				     =					ordered_inputs["attention_mask"].dtype
																					_lowerCAmelCase  :							Optional[Any]				     =					torch.cat(
																					    [ordered_inputs["attention_mask"], torch.ones(__a,    __a,    dtype=__a)],    dim=1)

														return ordered_inputs







							@property
							def      snake_case__   (     self):

														'''simple docstring'''

														return 13





import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


_snake_case	=						"\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

_snake_case	=						"\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

_snake_case	=						"\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"



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







							def      snake_case__   (     self):

														'''simple docstring'''

														return datasets.MetricInfo(
														    description=_DESCRIPTION,    citation=_CITATION,    inputs_description=_KWARGS_DESCRIPTION,    features=datasets.Features(
														        {
														            "predictions": datasets.Sequence(datasets.Value("string",    id="token"),    id="sequence"),
														            "references": datasets.Sequence(
														                datasets.Sequence(datasets.Value("string",    id="token"),    id="sequence"),    id="references"),
														        }),    codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"],    reference_urls=[
														        "https://en.wikipedia.org/wiki/BLEU",
														        "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
														    ],    )







							def      snake_case__   (     self,    __a,    __a,    __a=4,    __a=False):

														'''simple docstring'''

														_lowerCAmelCase  :							List[str]				     =					compute_bleu(
														    reference_corpus=__a,    translation_corpus=__a,    max_order=__a,    smooth=__a)
														((_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase))  :							Dict				     =					score
														return {
														    "bleu": bleu,
														    "precisions": precisions,
														    "brevity_penalty": bp,
														    "length_ratio": ratio,
														    "translation_length": translation_length,
														    "reference_length": reference_length,
														}
