




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

import datasets
from datasets import logging


UpperCAmelCase_						="""\

"""

UpperCAmelCase_						="""
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
"""

UpperCAmelCase_						="""
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to 'cuda' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        78.22
        >>> print(round(results[\"perplexities\"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = datasets.load_dataset(\"wikitext\",
        ...                                     \"wikitext-2-raw-v1\",
        ...                                     split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!='']
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        60.35
        >>> print(round(results[\"perplexities\"][0], 2))
        81.12
"""


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





				'''simple docstring'''



				def       __snake_case		( self						):
											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       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_       , UpperCAmelCase_ = 16       , UpperCAmelCase_ = True       , UpperCAmelCase_=None						):
											if device is not None:
																		assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
																		if device == "gpu":
																									lowerCAmelCase   =		'''cuda'''
											else:
																		lowerCAmelCase   =		'''cuda''' if torch.cuda.is_available() else '''cpu'''

											lowerCAmelCase   =		AutoModelForCausalLM.from_pretrained(UpperCAmelCase_						)
											lowerCAmelCase   =		model.to(UpperCAmelCase_						)

											lowerCAmelCase   =		AutoTokenizer.from_pretrained(UpperCAmelCase_						)

											# 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:
																		lowerCAmelCase   =		list(tokenizer.special_tokens_map_extended.values()						)
																		# check that the model already has at least one special token defined
																		assert (
																		    len(UpperCAmelCase_						) > 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"
																		lowerCAmelCase   =		model.config.max_length - 1
											else:
																		lowerCAmelCase   =		model.config.max_length

											lowerCAmelCase   =		tokenizer(
											    UpperCAmelCase_       , add_special_tokens=UpperCAmelCase_       , padding=UpperCAmelCase_       , truncation=UpperCAmelCase_       , max_length=UpperCAmelCase_       , return_tensors='''pt'''       , return_attention_mask=UpperCAmelCase_       , ).to(UpperCAmelCase_						)

											lowerCAmelCase   =		encodings['''input_ids''']
											lowerCAmelCase   =		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."

											lowerCAmelCase   =		[]
											lowerCAmelCase   =		CrossEntropyLoss(reduction='''none'''						)

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

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

																		lowerCAmelCase   =		encoded_batch

																		with torch.no_grad():
																									lowerCAmelCase   =		model(UpperCAmelCase_       , attention_mask=UpperCAmelCase_						).logits

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

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

																		ppls += perplexity_batch.tolist()

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









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

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase_						=logging.get_logger(__name__)

UpperCAmelCase_						={
    """vocab_file""": """vocab.txt""",
    """merges_file""": """bpe.codes""",
}

UpperCAmelCase_						={
    """vocab_file""": {
        """vinai/phobert-base""": """https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt""",
        """vinai/phobert-large""": """https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt""",
    },
    """merges_file""": {
        """vinai/phobert-base""": """https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes""",
        """vinai/phobert-large""": """https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes""",
    },
}

UpperCAmelCase_						={
    """vinai/phobert-base""": 256,
    """vinai/phobert-large""": 256,
}



def       UpperCAmelCase       (     _snake_case							):
							lowerCAmelCase   =		set()
							lowerCAmelCase   =		word[0]
							for char in word[1:]:
														pairs.add((prev_char, char)							)
														lowerCAmelCase   =		char

							lowerCAmelCase   =		set(_snake_case							)
							return pairs


class 							__UpperCamelCase			( __UpperCAmelCase  ):





				'''simple docstring'''



				__a							: Union[str, Any]										=VOCAB_FILES_NAMES
				__a							: Optional[Any]										=PRETRAINED_VOCAB_FILES_MAP
				__a							: Optional[int]										=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES



				def __init__( self       , UpperCAmelCase_       , UpperCAmelCase_       , UpperCAmelCase_="<s>"       , UpperCAmelCase_="</s>"       , UpperCAmelCase_="</s>"       , UpperCAmelCase_="<s>"       , UpperCAmelCase_="<unk>"       , UpperCAmelCase_="<pad>"       , UpperCAmelCase_="<mask>"       , **UpperCAmelCase_       , ):
											super().__init__(
											    bos_token=UpperCAmelCase_       , eos_token=UpperCAmelCase_       , unk_token=UpperCAmelCase_       , sep_token=UpperCAmelCase_       , cls_token=UpperCAmelCase_       , pad_token=UpperCAmelCase_       , mask_token=UpperCAmelCase_       , **UpperCAmelCase_       , )

											lowerCAmelCase   =		vocab_file
											lowerCAmelCase   =		merges_file

											lowerCAmelCase   =		{}
											lowerCAmelCase   =		0
											lowerCAmelCase   =		1
											lowerCAmelCase   =		2
											lowerCAmelCase   =		3

											self.add_from_file(UpperCAmelCase_						)

											lowerCAmelCase   =		{v: k for k, v in self.encoder.items()}

											with open(UpperCAmelCase_       , encoding='''utf-8'''						) as merges_handle:
																		lowerCAmelCase   =		merges_handle.read().split('''\n'''						)[:-1]
											lowerCAmelCase   =		[tuple(merge.split()[:-1]						) for merge in merges]
											lowerCAmelCase   =		dict(zip(UpperCAmelCase_       , range(len(UpperCAmelCase_						)						)						)						)
											lowerCAmelCase   =		{}



				def       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_ = None						):

											if token_ids_a is None:
																		return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
											lowerCAmelCase   =		[self.cls_token_id]
											lowerCAmelCase   =		[self.sep_token_id]
											return cls + token_ids_a + sep + sep + token_ids_a + sep



				def       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_ = None       , UpperCAmelCase_ = False						):

											if already_has_special_tokens:
																		return super().get_special_tokens_mask(
																		    token_ids_a=UpperCAmelCase_       , token_ids_a=UpperCAmelCase_       , already_has_special_tokens=UpperCAmelCase_						)

											if token_ids_a is None:
																		return [1] + ([0] * len(UpperCAmelCase_						)) + [1]
											return [1] + ([0] * len(UpperCAmelCase_						)) + [1, 1] + ([0] * len(UpperCAmelCase_						)) + [1]



				def       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_ = None						):
											lowerCAmelCase   =		[self.sep_token_id]
											lowerCAmelCase   =		[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]



				@property
				def       __snake_case		( self						):
											return len(self.encoder						)



				def       __snake_case		( self						):
											return dict(self.encoder       , **self.added_tokens_encoder						)



				def       __snake_case		( self       , UpperCAmelCase_						):
											if token in self.cache:
																		return self.cache[token]
											lowerCAmelCase   =		tuple(UpperCAmelCase_						)
											lowerCAmelCase   =		tuple(list(word[:-1]						) + [word[-1] + '''</w>''']						)
											lowerCAmelCase   =		get_pairs(UpperCAmelCase_						)

											if not pairs:
																		return token

											while True:
																		lowerCAmelCase   =		min(UpperCAmelCase_       , key=lambda UpperCAmelCase_						: self.bpe_ranks.get(UpperCAmelCase_       , float('''inf'''						)						)						)
																		if bigram not in self.bpe_ranks:
																									break
																		lowerCAmelCase   ,     lowerCAmelCase   =		bigram
																		lowerCAmelCase   =		[]
																		lowerCAmelCase   =		0
																		while i < len(UpperCAmelCase_						):
																									try:
																																lowerCAmelCase   =		word.index(UpperCAmelCase_       , UpperCAmelCase_						)
																									except ValueError:
																																new_word.extend(word[i:]						)
																																break
																									else:
																																new_word.extend(word[i:j]						)
																																lowerCAmelCase   =		j

																									if word[i] == first and i < len(UpperCAmelCase_						) - 1 and word[i + 1] == second:
																																new_word.append(first + second						)
																																i += 2
																									else:
																																new_word.append(word[i]						)
																																i += 1
																		lowerCAmelCase   =		tuple(UpperCAmelCase_						)
																		lowerCAmelCase   =		new_word
																		if len(UpperCAmelCase_						) == 1:
																									break
																		else:
																									lowerCAmelCase   =		get_pairs(UpperCAmelCase_						)
											lowerCAmelCase   =		'''@@ '''.join(UpperCAmelCase_						)
											lowerCAmelCase   =		word[:-4]
											lowerCAmelCase   =		word
											return word



				def       __snake_case		( self       , UpperCAmelCase_						):
											lowerCAmelCase   =		[]

											lowerCAmelCase   =		re.findall(r'''\S+\n?'''       , UpperCAmelCase_						)

											for token in words:
																		split_tokens.extend(list(self.bpe(UpperCAmelCase_						).split(''' '''						)						)						)
											return split_tokens



				def       __snake_case		( self       , UpperCAmelCase_						):
											return self.encoder.get(UpperCAmelCase_       , self.encoder.get(self.unk_token						)						)



				def       __snake_case		( self       , UpperCAmelCase_						):
											return self.decoder.get(UpperCAmelCase_       , self.unk_token						)



				def       __snake_case		( self       , UpperCAmelCase_						):
											lowerCAmelCase   =		''' '''.join(UpperCAmelCase_						).replace('''@@ '''       , ''''''						).strip()
											return out_string



				def       __snake_case		( self       , UpperCAmelCase_       , UpperCAmelCase_ = None						):
											if not os.path.isdir(UpperCAmelCase_						):
																		logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""						)
																		return
											lowerCAmelCase   =		os.path.join(
											    UpperCAmelCase_       , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']						)
											lowerCAmelCase   =		os.path.join(
											    UpperCAmelCase_       , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']						)

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

											if os.path.abspath(self.merges_file						) != os.path.abspath(UpperCAmelCase_						):
																		copyfile(self.merges_file       , UpperCAmelCase_						)

											return out_vocab_file, out_merge_file






				def       __snake_case		( self       , UpperCAmelCase_						):
											if isinstance(UpperCAmelCase_       , UpperCAmelCase_						):
																		try:
																									with open(UpperCAmelCase_       , '''r'''       , encoding='''utf-8'''						) as fd:
																																self.add_from_file(UpperCAmelCase_						)
																		except FileNotFoundError as fnfe:
																									raise fnfe
																		except UnicodeError:
																									raise Exception(F"""Incorrect encoding detected in {f}, please rebuild the dataset"""						)
																		return

											lowerCAmelCase   =		f.readlines()
											for lineTmp in lines:
																		lowerCAmelCase   =		lineTmp.strip()
																		lowerCAmelCase   =		line.rfind(''' '''						)
																		if idx == -1:
																									raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\''''						)
																		lowerCAmelCase   =		line[:idx]
																		lowerCAmelCase   =		len(self.encoder						)



