


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

import sentencepiece as spm

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


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

lowerCamelCase__							:						List[str]							     =   """▁"""

lowerCamelCase__							:						Optional[int]							     =   {"""vocab_file""": """sentencepiece.bpe.model"""}

lowerCamelCase__							:						Optional[int]							     =   {
    """vocab_file""": {
        """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""",
    }
}

lowerCamelCase__							:						List[Any]							     =   {
    """facebook/xglm-564M""": 2_0_4_8,
}
class 		__magic_name__						(snake_case_				):





     '''simple docstring'''



     __lowercase				:							Optional[Any]	   =       VOCAB_FILES_NAMES
     __lowercase				:							Optional[Any]	   =       PRETRAINED_VOCAB_FILES_MAP
     __lowercase				:							List[str]	   =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __lowercase				:							List[Any]	   =       ['input_ids', 'attention_mask']

     def __init__(					self:int     ,		_a:List[Any]     ,		_a:List[str]="<s>"     ,		_a:str="</s>"     ,		_a:int="</s>"     ,		_a:Optional[int]="<s>"     ,		_a:Any="<unk>"     ,		_a:int="<pad>"     ,		_a:Optional[Dict[str, Any]] = None     ,		**_a:int     ,		):
       snake_case__						= {} if sp_model_kwargs is None else sp_model_kwargs

       # Compatibility with the original tokenizer
       snake_case__						= 7
       snake_case__						= [F"""<madeupword{i}>""" for i in range(self.num_madeup_words   )]

       snake_case__						= kwargs.get('''additional_special_tokens'''     ,		[]   )
       kwargs["additional_special_tokens"] += [
           word for word in madeup_words if word not in kwargs["additional_special_tokens"]
       ]

       super().__init__(
           bos_token=_a     ,		eos_token=_a     ,		unk_token=_a     ,		sep_token=_a     ,		cls_token=_a     ,		pad_token=_a     ,		sp_model_kwargs=self.sp_model_kwargs     ,		**_a     ,		)

       snake_case__						= spm.SentencePieceProcessor(**self.sp_model_kwargs   )
       self.sp_model.Load(str(_a   )   )
       snake_case__						= vocab_file

       # Original fairseq vocab and spm vocab must be "aligned":
       # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
       # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
       # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
       # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

       # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
       snake_case__						= 1

       # Mimic fairseq token-to-id alignment for the first 4 token
       snake_case__						= {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

       snake_case__						= len(self.sp_model   )
       snake_case__						= {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words   )}
       self.fairseq_tokens_to_ids.update(_a   )

       snake_case__						= {v: k for k, v in self.fairseq_tokens_to_ids.items()}

     def __getstate__(					self:Optional[int]   ):
       snake_case__						= self.__dict__.copy()
       snake_case__						= None
       snake_case__						= self.sp_model.serialized_model_proto()
       return state

     def __setstate__(					self:Optional[Any]     ,		_a:Union[str, Any]   ):
       snake_case__						= d

       # for backward compatibility
       if not hasattr(self     ,		'''sp_model_kwargs'''   ):
         snake_case__						= {}

       snake_case__						= spm.SentencePieceProcessor(**self.sp_model_kwargs   )
       self.sp_model.LoadFromSerializedProto(self.sp_model_proto   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Any     ,		_a:List[int]     ,		_a:Optional[List[int]] = None   ):

       if token_ids_a is None:
         return [self.sep_token_id] + token_ids_a
       snake_case__						= [self.sep_token_id]
       return sep + token_ids_a + sep + sep + token_ids_a

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict     ,		_a:List[int]     ,		_a:Optional[List[int]] = None     ,		_a:bool = False   ):

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

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

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:List[int]     ,		_a:Optional[List[int]] = None   ):
       snake_case__						= [self.sep_token_id]

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

     @property
     def 	SCREAMING_SNAKE_CASE__						(					self:Tuple   ):
       return len(self.sp_model   ) + self.fairseq_offset + self.num_madeup_words

     def 	SCREAMING_SNAKE_CASE__						(					self:str   ):
       snake_case__						= {self.convert_ids_to_tokens(_a   ): i for i in range(self.vocab_size   )}
       vocab.update(self.added_tokens_encoder   )
       return vocab

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:str   ):
       return self.sp_model.encode(_a     ,		out_type=_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:str     ,		_a:Optional[Any]   ):
       if token in self.fairseq_tokens_to_ids:
         return self.fairseq_tokens_to_ids[token]
       snake_case__						= self.sp_model.PieceToId(_a   )

       # Need to return unknown token if the SP model returned 0
       return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

     def 	SCREAMING_SNAKE_CASE__						(					self:Tuple     ,		_a:List[Any]   ):
       if index in self.fairseq_ids_to_tokens:
         return self.fairseq_ids_to_tokens[index]
       return self.sp_model.IdToPiece(index - self.fairseq_offset   )

     def 	SCREAMING_SNAKE_CASE__						(					self:int     ,		_a:Any   ):
       snake_case__						= ''''''.join(_a   ).replace(_a     ,		''' '''   ).strip()
       return out_string







     def 	SCREAMING_SNAKE_CASE__						(					self:Tuple     ,		_a:str     ,		_a:Optional[str] = None   ):
       if not os.path.isdir(_a   ):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""   )
         return
       snake_case__						= os.path.join(
           _a     ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )

       if os.path.abspath(self.vocab_file   ) != os.path.abspath(_a   ) and os.path.isfile(self.vocab_file   ):
         copyfile(self.vocab_file     ,		_a   )
       elif not os.path.isfile(self.vocab_file   ):
         with open(_a     ,		'''wb'''   ) as fi:
           snake_case__						= self.sp_model.serialized_model_proto()
           fi.write(_a   )

       return (out_vocab_file,)






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

import datasets
from datasets import logging


_lowerCamelCase    :		List[str]		      =    """\

"""

_lowerCamelCase    :		Optional[int]		      =    """
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
"""

_lowerCamelCase    :		List[Any]		      =    """
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 						lowercase    (							datasets.Metric):
						'''simple docstring'''


						def       lowerCamelCase_				(  self    :				List[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    :				List[Any]       ,	snake_case    :				Optional[int]       ,	snake_case    :				int       ,	snake_case    :				int = 16       ,	snake_case    :				bool = True       ,	snake_case    :				Dict=None	):



											'''simple docstring'''


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

											SCREAMING_SNAKE_CASE							:     Any						=				AutoModelForCausalLM.from_pretrained(snake_case	)
											SCREAMING_SNAKE_CASE							:     Dict						=				model.to(snake_case	)

											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				AutoTokenizer.from_pretrained(snake_case	)

											# 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:
																SCREAMING_SNAKE_CASE							:     str						=				list(tokenizer.special_tokens_map_extended.values()	)
																# check that the model already has at least one special token defined
																assert (
																    len(snake_case	) > 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"
																SCREAMING_SNAKE_CASE							:     List[str]						=				model.config.max_length - 1
											else:
																SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				model.config.max_length

											SCREAMING_SNAKE_CASE							:     Tuple						=				tokenizer(
											    snake_case       ,	add_special_tokens=snake_case       ,	padding=snake_case       ,	truncation=snake_case       ,	max_length=snake_case       ,	return_tensors='pt'       ,	return_attention_mask=snake_case       ,	).to(snake_case	)

											SCREAMING_SNAKE_CASE							:     List[Any]						=				encodings['input_ids']
											SCREAMING_SNAKE_CASE							:     Dict						=				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."

											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				[]
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				CrossEntropyLoss(reduction='none'	)

											for start_index in logging.tqdm(range(0       ,	len(snake_case	)       ,	snake_case	)	):
																SCREAMING_SNAKE_CASE							:     Dict						=				min(start_index + batch_size       ,	len(snake_case	)	)
																SCREAMING_SNAKE_CASE							:     List[str]						=				encoded_texts[start_index:end_index]
																SCREAMING_SNAKE_CASE							:     Optional[int]						=				attn_masks[start_index:end_index]

																if add_start_token:
																					SCREAMING_SNAKE_CASE							:     List[Any]						=				torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0	)	).to(snake_case	)
																					SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				torch.cat([bos_tokens_tensor, encoded_batch]       ,	dim=1	)
																					SCREAMING_SNAKE_CASE							:     int						=				torch.cat(
																					    [torch.ones(bos_tokens_tensor.size()       ,	dtype=torch.intaa	).to(snake_case	), attn_mask]       ,	dim=1	)

																SCREAMING_SNAKE_CASE							:     Optional[Any]						=				encoded_batch

																with torch.no_grad():
																					SCREAMING_SNAKE_CASE							:     str						=				model(snake_case       ,	attention_mask=snake_case	).logits

																SCREAMING_SNAKE_CASE							:     Optional[Any]						=				out_logits[..., :-1, :].contiguous()
																SCREAMING_SNAKE_CASE							:     Optional[int]						=				labels[..., 1:].contiguous()
																SCREAMING_SNAKE_CASE							:     Optional[int]						=				attn_mask[..., 1:].contiguous()

																SCREAMING_SNAKE_CASE							:     Optional[int]						=				torch.expa(
																    (loss_fct(shift_logits.transpose(1       ,	2	)       ,	snake_case	) * shift_attention_mask_batch).sum(1	)
																    / shift_attention_mask_batch.sum(1	)	)

																ppls += perplexity_batch.tolist()

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