


"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


SCREAMING_SNAKE_CASE :    Tuple									=				logging.get_logger(__name__)

SCREAMING_SNAKE_CASE :    Tuple									=				{
    """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""",
}



class 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		lowerCamelCase__				='nllb-moe'
		lowerCamelCase__				=['past_key_values']
		lowerCamelCase__				={'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}



		def __init__(self				,       a_=12_81_12				,       a_=10_24				,       a_=12				,       a_=40_96				,       a_=16				,       a_=12				,       a_=40_96				,       a_=16				,       a_=0.05				,       a_=0.05				,       a_=True				,       a_=True				,       a_="relu"				,       a_=10_24				,       a_=0.1				,       a_=0.1				,       a_=0.0				,       a_=0.02				,       a_=2				,       a_=True				,       a_=False				,       a_="float32"				,       a_=False				,       a_=1_28				,       a_=64				,       a_=4				,       a_=4				,       a_=0.001				,       a_=0.001				,       a_="all"				,       a_=False				,       a_=False				,       a_=1.0				,       a_=0.2				,       a_=1				,       a_=0				,       a_=2				,       a_=False				,       **a_				,       ):





			'''simple docstring'''

			__snake_case	:						Optional[Any]						=				vocab_size
			__snake_case	:						int						=				max_position_embeddings
			__snake_case	:						int						=				d_model
			__snake_case	:						List[str]						=				encoder_ffn_dim
			__snake_case	:						Optional[Any]						=				encoder_layers
			__snake_case	:						Dict						=				encoder_attention_heads
			__snake_case	:						str						=				decoder_ffn_dim
			__snake_case	:						Dict						=				decoder_layers
			__snake_case	:						Union[str, Any]						=				decoder_attention_heads
			__snake_case	:						Optional[Any]						=				dropout
			__snake_case	:						Union[str, Any]						=				attention_dropout
			__snake_case	:						Union[str, Any]						=				activation_dropout
			__snake_case	:						List[Any]						=				activation_function
			__snake_case	:						int						=				init_std
			__snake_case	:						List[Any]						=				encoder_layerdrop
			__snake_case	:						Optional[Any]						=				decoder_layerdrop
			__snake_case	:						Tuple						=				use_cache
			__snake_case	:						Dict						=				encoder_layers
			__snake_case	:						List[str]						=				scale_embedding  # scale factor will be sqrt(d_model) if True
			__snake_case	:						List[str]						=				router_z_loss_coef
			__snake_case	:						int						=				router_aux_loss_coef
			__snake_case	:						Union[str, Any]						=				decoder_sparse_step
			__snake_case	:						Tuple						=				encoder_sparse_step
			__snake_case	:						int						=				num_experts
			__snake_case	:						List[Any]						=				expert_capacity
			__snake_case	:						int						=				router_bias
			if router_dtype not in ["float32", "float16", "bfloat16"]:
				raise ValueError(f"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}"""					)
			__snake_case	:						Optional[int]						=				router_dtype

			__snake_case	:						Tuple						=				router_ignore_padding_tokens
			__snake_case	:						List[Any]						=				batch_prioritized_routing
			__snake_case	:						Optional[int]						=				second_expert_policy
			__snake_case	:						Any						=				normalize_router_prob_before_dropping
			__snake_case	:						List[Any]						=				moe_eval_capacity_token_fraction
			__snake_case	:						Optional[int]						=				moe_token_dropout
			__snake_case	:						int						=				output_router_logits
			super().__init__(
			    pad_token_id=a_				,       bos_token_id=a_				,       eos_token_id=a_				,       is_encoder_decoder=a_				,       decoder_start_token_id=a_				,       **a_				,       )









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

import datasets
from datasets import logging


SCREAMING_SNAKE_CASE :    Union[str, Any]									=				"""\

"""

SCREAMING_SNAKE_CASE :    Any									=				"""
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
"""

SCREAMING_SNAKE_CASE :    Dict									=				"""
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 				SCREAMING_SNAKE_CASE  (self					):





			'''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 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_ = 16				,       a_ = True				,       a_=None					):





			'''simple docstring'''

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

			__snake_case	:						int						=				AutoModelForCausalLM.from_pretrained(a_					)
			__snake_case	:						Optional[int]						=				model.to(a_					)

			__snake_case	:						Optional[int]						=				AutoTokenizer.from_pretrained(a_					)

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

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

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

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

			for start_index in logging.tqdm(range(0				,       len(a_					)				,       a_					)					):
				__snake_case	:						Optional[int]						=				min(start_index + batch_size				,       len(a_					)					)
				__snake_case	:						int						=				encoded_texts[start_index:end_index]
				__snake_case	:						Optional[int]						=				attn_masks[start_index:end_index]

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

				__snake_case	:						List[Any]						=				encoded_batch

				with torch.no_grad():
					__snake_case	:						List[str]						=				model(a_				,       attention_mask=a_					).logits

				__snake_case	:						List[str]						=				out_logits[..., :-1, :].contiguous()
				__snake_case	:						int						=				labels[..., 1:].contiguous()
				__snake_case	:						int						=				attn_mask[..., 1:].contiguous()

				__snake_case	:						Tuple						=				torch.expa(
				    (loss_fct(shift_logits.transpose(1				,       2					)				,       a_					) * shift_attention_mask_batch).sum(1					)
				    / shift_attention_mask_batch.sum(1					)					)

				ppls += perplexity_batch.tolist()

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





