'''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_	   =			'\\n\n'

SCREAMING_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'

SCREAMING_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    a (       datasets.Metric				):



  """simple docstring"""







  def    lowercase_  (							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    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_ = 16   ,    snake_case_ = True   ,    snake_case_=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:					Optional[Any]		= """cuda"""
    else:
      __UpperCAmelCase:					Union[str, Any]		= """cuda""" if torch.cuda.is_available() else """cpu"""

    __UpperCAmelCase:					Optional[int]		= AutoModelForCausalLM.from_pretrained(snake_case_					)
    __UpperCAmelCase:					Dict		= model.to(snake_case_					)

    __UpperCAmelCase:					int		= 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:
      __UpperCAmelCase:					Any		= 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"
      __UpperCAmelCase:					Tuple		= model.config.max_length - 1
    else:
      __UpperCAmelCase:					Tuple		= model.config.max_length

    __UpperCAmelCase:					Optional[Any]		= 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_					)

    __UpperCAmelCase:					List[Any]		= encodings["""input_ids"""]
    __UpperCAmelCase:					Tuple		= 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:					Any		= []
    __UpperCAmelCase:					Optional[Any]		= CrossEntropyLoss(reduction="""none"""					)

    for start_index in logging.tqdm(range(0   ,    len(snake_case_					)   ,    snake_case_					)					):
      __UpperCAmelCase:					str		= min(start_index + batch_size   ,    len(snake_case_					)					)
      __UpperCAmelCase:					Optional[Any]		= encoded_texts[start_index:end_index]
      __UpperCAmelCase:					Union[str, Any]		= attn_masks[start_index:end_index]

      if add_start_token:
        __UpperCAmelCase:					Optional[int]		= torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0					)					).to(snake_case_					)
        __UpperCAmelCase:					int		= torch.cat([bos_tokens_tensor, encoded_batch]   ,    dim=1					)
        __UpperCAmelCase:					Dict		= torch.cat(
            [torch.ones(bos_tokens_tensor.size()   ,    dtype=torch.intaa					).to(snake_case_					), attn_mask]   ,    dim=1					)

      __UpperCAmelCase:					Union[str, Any]		= encoded_batch

      with torch.no_grad():
        __UpperCAmelCase:					Any		= model(snake_case_   ,    attention_mask=snake_case_					).logits

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

      __UpperCAmelCase:					str		= 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_					)}
'''simple docstring'''






import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
    import jax.numpy as jnp

    from transformers.models.albert.modeling_flax_albert import (
        FlaxAlbertForMaskedLM,
        FlaxAlbertForMultipleChoice,
        FlaxAlbertForPreTraining,
        FlaxAlbertForQuestionAnswering,
        FlaxAlbertForSequenceClassification,
        FlaxAlbertForTokenClassification,
        FlaxAlbertModel,
    )




class    a (       unittest.TestCase				):



  """simple docstring"""







  def __init__(							self   ,    snake_case_   ,    snake_case_=13   ,    snake_case_=7   ,    snake_case_=True   ,    snake_case_=True   ,    snake_case_=True   ,    snake_case_=True   ,    snake_case_=99   ,    snake_case_=32   ,    snake_case_=5   ,    snake_case_=4   ,    snake_case_=37   ,    snake_case_="gelu"   ,    snake_case_=0.1   ,    snake_case_=0.1   ,    snake_case_=512   ,    snake_case_=16   ,    snake_case_=2   ,    snake_case_=0.0_2   ,    snake_case_=4   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= parent
    __UpperCAmelCase:					List[str]		= batch_size
    __UpperCAmelCase:					Optional[int]		= seq_length
    __UpperCAmelCase:					Optional[Any]		= is_training
    __UpperCAmelCase:					Any		= use_attention_mask
    __UpperCAmelCase:					List[str]		= use_token_type_ids
    __UpperCAmelCase:					List[str]		= use_labels
    __UpperCAmelCase:					List[str]		= vocab_size
    __UpperCAmelCase:					Optional[Any]		= hidden_size
    __UpperCAmelCase:					List[Any]		= num_hidden_layers
    __UpperCAmelCase:					List[Any]		= num_attention_heads
    __UpperCAmelCase:					Tuple		= intermediate_size
    __UpperCAmelCase:					Dict		= hidden_act
    __UpperCAmelCase:					Dict		= hidden_dropout_prob
    __UpperCAmelCase:					Tuple		= attention_probs_dropout_prob
    __UpperCAmelCase:					List[str]		= max_position_embeddings
    __UpperCAmelCase:					List[Any]		= type_vocab_size
    __UpperCAmelCase:					List[Any]		= type_sequence_label_size
    __UpperCAmelCase:					List[str]		= initializer_range
    __UpperCAmelCase:					List[Any]		= num_choices







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					int		= ids_tensor([self.batch_size, self.seq_length]   ,    self.vocab_size					)

    __UpperCAmelCase:					str		= None
    if self.use_attention_mask:
      __UpperCAmelCase:					Any		= random_attention_mask([self.batch_size, self.seq_length]					)

    __UpperCAmelCase:					List[Any]		= None
    if self.use_token_type_ids:
      __UpperCAmelCase:					Optional[int]		= ids_tensor([self.batch_size, self.seq_length]   ,    self.type_vocab_size					)

    __UpperCAmelCase:					List[Any]		= AlbertConfig(
        vocab_size=self.vocab_size   ,    hidden_size=self.hidden_size   ,    num_hidden_layers=self.num_hidden_layers   ,    num_attention_heads=self.num_attention_heads   ,    intermediate_size=self.intermediate_size   ,    hidden_act=self.hidden_act   ,    hidden_dropout_prob=self.hidden_dropout_prob   ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,    max_position_embeddings=self.max_position_embeddings   ,    type_vocab_size=self.type_vocab_size   ,    is_decoder=snake_case_   ,    initializer_range=self.initializer_range   ,    )

    return config, input_ids, token_type_ids, attention_mask







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Tuple		= self.prepare_config_and_inputs()
    __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase:					List[str]		= config_and_inputs
    __UpperCAmelCase:					List[Any]		= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
    return config, inputs_dict




@require_flax
class    a (       __lowerCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					(
      (
          FlaxAlbertModel,
          FlaxAlbertForPreTraining,
          FlaxAlbertForMaskedLM,
          FlaxAlbertForMultipleChoice,
          FlaxAlbertForQuestionAnswering,
          FlaxAlbertForSequenceClassification,
          FlaxAlbertForTokenClassification,
          FlaxAlbertForQuestionAnswering,
      )
      if is_flax_available()
      else ()
  )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Union[str, Any]		= FlaxAlbertModelTester(self					)







  @slow
  def    lowercase_  (							self					):

    '''simple docstring'''







    for model_class_name in self.all_model_classes:
      __UpperCAmelCase:					str		= model_class_name.from_pretrained("""albert-base-v2"""					)
      __UpperCAmelCase:					int		= model(np.ones((1, 1)					)					)
      self.assertIsNotNone(snake_case_					)




@require_flax
class    a (       unittest.TestCase				):



  """simple docstring"""







  @slow
  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					str		= FlaxAlbertModel.from_pretrained("""albert-base-v2"""					)
    __UpperCAmelCase:					Dict		= np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]					)
    __UpperCAmelCase:					int		= np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
    __UpperCAmelCase:					Optional[int]		= model(snake_case_   ,    attention_mask=snake_case_					)[0]
    __UpperCAmelCase:					Optional[int]		= (1, 11, 768)
    self.assertEqual(output.shape   ,    snake_case_					)
    __UpperCAmelCase:					str		= np.array(
        [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]]					)

    self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]   ,    snake_case_   ,    atol=1e-4					)					)