


import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


__snake_case            =   "\\n\n"

__snake_case            =   "\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n"

__snake_case            =   "\nArgs:\n    model_id (str): model used for calculating Perplexity\n            NOTE: Perplexity can only be calculated for causal language models.\n                    This includes models such as gpt2, causal variations of bert,\n                    causal versions of t5, and more (the full list can be found\n                    in the AutoModelForCausalLM documentation here:\n                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n    input_texts (list of str): input text, each separate text snippet\n        is one list entry.\n    batch_size (int): the batch size to run texts through the model. Defaults to 16.\n    add_start_token (bool): whether to add the start token to the texts,\n        so the perplexity can include the probability of the first word. Defaults to True.\n    device (str): device to run on, defaults to 'cuda' when available\nReturns:\n    perplexity: dictionary containing the perplexity scores for the texts\n        in the input list, as well as the mean perplexity. If one of the input texts is\n        longer than the max input length of the model, then it is truncated to the\n        max length for the perplexity computation.\nExamples:\n    Example 1:\n        >>> perplexity = datasets.load_metric(\"perplexity\")\n        >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]\n        >>> results = perplexity.compute(model_id='gpt2',\n        ...                              add_start_token=False,\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        ['perplexities', 'mean_perplexity']\n        >>> print(round(results[\"mean_perplexity\"], 2))\n        78.22\n        >>> print(round(results[\"perplexities\"][0], 2))\n        11.11\n\n    Example 2:\n        >>> perplexity = datasets.load_metric(\"perplexity\")\n        >>> input_texts = datasets.load_dataset(\"wikitext\",\n        ...                                     \"wikitext-2-raw-v1\",\n        ...                                     split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS\n        [...]\n        >>> input_texts = [s for s in input_texts if s!='']\n        >>> results = perplexity.compute(model_id='gpt2',\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        ['perplexities', 'mean_perplexity']\n        >>> print(round(results[\"mean_perplexity\"], 2))\n        60.35\n        >>> print(round(results[\"perplexities\"][0], 2))\n        81.12\n"




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




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







						"""simple docstring"""







						return datasets.MetricInfo(
						    description=_DESCRIPTION       ,       citation=_CITATION       ,       inputs_description=_KWARGS_DESCRIPTION       ,       features=datasets.Features(
						        {
						            """input_texts""": datasets.Value("""string"""						),
						        }						)       ,       reference_urls=["""https://huggingface.co/docs/transformers/perplexity"""]       ,       )





			def   lowerCamelCase_					(						self							:		Any       ,       __magic_name__							:		int       ,       __magic_name__							:		str       ,       __magic_name__							:		int = 1_6       ,       __magic_name__							:		bool = True       ,       __magic_name__							:		int=None						):







						"""simple docstring"""







						if device is not None:
									assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
									if device == "gpu":
												UpperCamelCase         =					"""cuda"""
						else:
									UpperCamelCase         =					"""cuda""" if torch.cuda.is_available() else """cpu"""

						UpperCamelCase         =					AutoModelForCausalLM.from_pretrained(__magic_name__						)
						UpperCamelCase         =					model.to(__magic_name__						)

						UpperCamelCase         =					AutoTokenizer.from_pretrained(__magic_name__						)

						# if batch_size > 1 (which generally leads to padding being required), and
						# if there is not an already assigned pad_token, assign an existing
						# special token to also be the padding token
						if tokenizer.pad_token is None and batch_size > 1:
									UpperCamelCase         =					list(tokenizer.special_tokens_map_extended.values()						)
									# check that the model already has at least one special token defined
									assert (
									    len(__magic_name__						) > 0
									), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
									# assign one of the special tokens to also be the pad token
									tokenizer.add_special_tokens({"""pad_token""": existing_special_tokens[0]}						)

						if add_start_token:
									# leave room for <BOS> token to be added:
									assert (
									    tokenizer.bos_token is not None
									), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
									UpperCamelCase         =					model.config.max_length - 1
						else:
									UpperCamelCase         =					model.config.max_length

						UpperCamelCase         =					tokenizer(
						    __magic_name__       ,       add_special_tokens=__magic_name__       ,       padding=__magic_name__       ,       truncation=__magic_name__       ,       max_length=__magic_name__       ,       return_tensors="""pt"""       ,       return_attention_mask=__magic_name__       ,       ).to(__magic_name__						)

						UpperCamelCase         =					encodings["""input_ids"""]
						UpperCamelCase         =					encodings["""attention_mask"""]

						# check that each input is long enough:
						if add_start_token:
									assert torch.all(torch.ge(attn_masks.sum(1						)       ,       1						)						), "Each input text must be at least one token long."
						else:
									assert torch.all(
									    torch.ge(attn_masks.sum(1						)       ,       2						)						), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

						UpperCamelCase         =					[]
						UpperCamelCase         =					CrossEntropyLoss(reduction="""none"""						)

						for start_index in logging.tqdm(range(0       ,       len(__magic_name__						)       ,       __magic_name__						)						):
									UpperCamelCase         =					min(start_index + batch_size       ,       len(__magic_name__						)						)
									UpperCamelCase         =					encoded_texts[start_index:end_index]
									UpperCamelCase         =					attn_masks[start_index:end_index]

									if add_start_token:
												UpperCamelCase         =					torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0						)						).to(__magic_name__						)
												UpperCamelCase         =					torch.cat([bos_tokens_tensor, encoded_batch]       ,       dim=1						)
												UpperCamelCase         =					torch.cat(
												    [torch.ones(bos_tokens_tensor.size()       ,       dtype=torch.intaa						).to(__magic_name__						), attn_mask]       ,       dim=1						)

									UpperCamelCase         =					encoded_batch

									with torch.no_grad():
												UpperCamelCase         =					model(__magic_name__       ,       attention_mask=__magic_name__						).logits

									UpperCamelCase         =					out_logits[..., :-1, :].contiguous()
									UpperCamelCase         =					labels[..., 1:].contiguous()
									UpperCamelCase         =					attn_mask[..., 1:].contiguous()

									UpperCamelCase         =					torch.expa(
									    (loss_fct(shift_logits.transpose(1       ,       2						)       ,       __magic_name__						) * shift_attention_mask_batch).sum(1						)
									    / shift_attention_mask_batch.sum(1						)						)

									ppls += perplexity_batch.tolist()

						return {"perplexities": ppls, "mean_perplexity": np.mean(__magic_name__						)}








import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
			from .tokenization_mbart import MBartTokenizer
else:
			__snake_case            =   None


__snake_case            =   logging.get_logger(__name__)


__snake_case            =   {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}

__snake_case            =   {
    "vocab_file": {
        "facebook/mbart-large-en-ro": (
            "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"
        ),
        "facebook/mbart-large-cc25": (
            "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"
        ),
    },
    "tokenizer_file": {
        "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json",
        "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json",
    },
}

__snake_case            =   {
    "facebook/mbart-large-en-ro": 1_024,
    "facebook/mbart-large-cc25": 1_024,
}

# fmt: off
__snake_case            =   ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"]




class    UpperCAmelCase					(       __snake_case    ):
			lowercase						= VOCAB_FILES_NAMES
			lowercase						= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			lowercase						= PRETRAINED_VOCAB_FILES_MAP
			lowercase						= ["""input_ids""", """attention_mask"""]
			lowercase						= MBartTokenizer

			lowercase						= []
			lowercase						= []




			def __init__(						self							:		Optional[int]       ,       __magic_name__							:		str=None       ,       __magic_name__							:		Optional[int]=None       ,       __magic_name__							:		Dict="<s>"       ,       __magic_name__							:		Union[str, Any]="</s>"       ,       __magic_name__							:		List[str]="</s>"       ,       __magic_name__							:		Optional[int]="<s>"       ,       __magic_name__							:		int="<unk>"       ,       __magic_name__							:		str="<pad>"       ,       __magic_name__							:		List[str]="<mask>"       ,       __magic_name__							:		Tuple=None       ,       __magic_name__							:		Dict=None       ,       __magic_name__							:		Dict=None       ,       **__magic_name__							:		Tuple       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					AddedToken(__magic_name__       ,       lstrip=__magic_name__       ,       rstrip=__magic_name__						) if isinstance(__magic_name__       ,       __magic_name__						) else mask_token

						super().__init__(
						    vocab_file=__magic_name__       ,       tokenizer_file=__magic_name__       ,       bos_token=__magic_name__       ,       eos_token=__magic_name__       ,       sep_token=__magic_name__       ,       cls_token=__magic_name__       ,       unk_token=__magic_name__       ,       pad_token=__magic_name__       ,       mask_token=__magic_name__       ,       src_lang=__magic_name__       ,       tgt_lang=__magic_name__       ,       additional_special_tokens=__magic_name__       ,       **__magic_name__       ,       )

						UpperCamelCase         =					vocab_file
						UpperCamelCase         =					False if not self.vocab_file else True

						UpperCamelCase         =					FAIRSEQ_LANGUAGE_CODES.copy()

						if additional_special_tokens is not None:
									# Only add those special tokens if they are not already there.
									_additional_special_tokens.extend(
									    [t for t in additional_special_tokens if t not in _additional_special_tokens]						)

						self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens}						)
						UpperCamelCase         =					{
						    lang_code: self.convert_tokens_to_ids(__magic_name__						) for lang_code in FAIRSEQ_LANGUAGE_CODES
						}

						UpperCamelCase         =					src_lang if src_lang is not None else """en_XX"""
						UpperCamelCase         =					self.convert_tokens_to_ids(self._src_lang						)
						UpperCamelCase         =					tgt_lang
						self.set_src_lang_special_tokens(self._src_lang						)




			@property
			def   lowerCamelCase_					(						self							:		int						):







						"""simple docstring"""







						return self._src_lang




			@src_lang.setter
			def   lowerCamelCase_					(						self							:		List[str]       ,       __magic_name__							:		str						):







						"""simple docstring"""







						UpperCamelCase         =					new_src_lang
						self.set_src_lang_special_tokens(self._src_lang						)




			def   lowerCamelCase_					(						self							:		Optional[Any]       ,       __magic_name__							:		List[int]       ,       __magic_name__							:		Optional[List[int]] = None						):







						"""simple docstring"""







						if token_ids_a is None:
									return self.prefix_tokens + token_ids_a + self.suffix_tokens
						# We don't expect to process pairs, but leave the pair logic for API consistency
						return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens




			def   lowerCamelCase_					(						self							:		int       ,       __magic_name__							:		List[int]       ,       __magic_name__							:		Optional[List[int]] = None						):







						"""simple docstring"""







						UpperCamelCase         =					[self.sep_token_id]
						UpperCamelCase         =					[self.cls_token_id]

						if token_ids_a is None:
									return len(cls + token_ids_a + sep						) * [0]
						return len(cls + token_ids_a + sep + sep + token_ids_a + sep						) * [0]




			def   lowerCamelCase_					(						self							:		int       ,       __magic_name__							:		List[Any]       ,       __magic_name__							:		str       ,       __magic_name__							:		Optional[str]       ,       __magic_name__							:		Optional[str]       ,       **__magic_name__							:		Tuple						):







						"""simple docstring"""







						if src_lang is None or tgt_lang is None:
									raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""						)
						UpperCamelCase         =					src_lang
						UpperCamelCase         =					self(__magic_name__       ,       add_special_tokens=__magic_name__       ,       return_tensors=__magic_name__       ,       **__magic_name__						)
						UpperCamelCase         =					self.convert_tokens_to_ids(__magic_name__						)
						UpperCamelCase         =					tgt_lang_id
						return inputs




			def   lowerCamelCase_					(						self							:		Dict       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		str = "en_XX"       ,       __magic_name__							:		Optional[List[str]] = None       ,       __magic_name__							:		str = "ro_RO"       ,       **__magic_name__							:		int       ,       ):







						"""simple docstring"""







						UpperCamelCase         =					src_lang
						UpperCamelCase         =					tgt_lang
						return super().prepare_seqaseq_batch(__magic_name__       ,       __magic_name__       ,       **__magic_name__						)




			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						return self.set_src_lang_special_tokens(self.src_lang						)




			def   lowerCamelCase_					(						self							:		Any						):







						"""simple docstring"""







						return self.set_tgt_lang_special_tokens(self.tgt_lang						)




			def   lowerCamelCase_					(						self							:		int       ,       __magic_name__							:		Union[str, Any]						):







						"""simple docstring"""







						UpperCamelCase         =					self.convert_tokens_to_ids(__magic_name__						)
						UpperCamelCase         =					[]
						UpperCamelCase         =					[self.eos_token_id, self.cur_lang_code]

						UpperCamelCase         =					self.convert_ids_to_tokens(self.prefix_tokens						)
						UpperCamelCase         =					self.convert_ids_to_tokens(self.suffix_tokens						)

						UpperCamelCase         =					processors.TemplateProcessing(
						    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,       pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,       special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,       self.prefix_tokens + self.suffix_tokens						)						)       ,       )




			def   lowerCamelCase_					(						self							:		Tuple       ,       __magic_name__							:		str						):







						"""simple docstring"""







						UpperCamelCase         =					self.convert_tokens_to_ids(__magic_name__						)
						UpperCamelCase         =					[]
						UpperCamelCase         =					[self.eos_token_id, self.cur_lang_code]

						UpperCamelCase         =					self.convert_ids_to_tokens(self.prefix_tokens						)
						UpperCamelCase         =					self.convert_ids_to_tokens(self.suffix_tokens						)

						UpperCamelCase         =					processors.TemplateProcessing(
						    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,       pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,       special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,       self.prefix_tokens + self.suffix_tokens						)						)       ,       )





			def   lowerCamelCase_					(						self							:		Any       ,       __magic_name__							:		str       ,       __magic_name__							:		Optional[str] = None						):







						"""simple docstring"""







						if not self.can_save_slow_tokenizer:
									raise ValueError(
									    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
									    """tokenizer."""						)

						if not os.path.isdir(__magic_name__						):
									logger.error(F'Vocabulary path ({save_directory}) should be a directory.'						)
									return
						UpperCamelCase         =					os.path.join(
						    __magic_name__       ,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]						)

						if os.path.abspath(self.vocab_file						) != os.path.abspath(__magic_name__						):
									copyfile(self.vocab_file       ,       __magic_name__						)

						return (out_vocab_file,)




