



'''simple docstring'''


import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
       DistilBertForMaskedLM,
       DistilBertForMultipleChoice,
       DistilBertForQuestionAnswering,
       DistilBertForSequenceClassification,
       DistilBertForTokenClassification,
       DistilBertModel,
   )

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    def __init__(  self      :					List[str]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					Optional[Any]=1_3  ,						UpperCamelCase__      :					Dict=7  ,						UpperCamelCase__      :					int=True  ,						UpperCamelCase__      :					Optional[Any]=True  ,						UpperCamelCase__      :					Dict=False  ,						UpperCamelCase__      :					int=True  ,						UpperCamelCase__      :					List[str]=9_9  ,						UpperCamelCase__      :					Optional[int]=3_2  ,						UpperCamelCase__      :					int=5  ,						UpperCamelCase__      :					str=4  ,						UpperCamelCase__      :					int=3_7  ,						UpperCamelCase__      :					Optional[int]="gelu"  ,						UpperCamelCase__      :					str=0.1  ,						UpperCamelCase__      :					Tuple=0.1  ,						UpperCamelCase__      :					int=5_1_2  ,						UpperCamelCase__      :					List[Any]=1_6  ,						UpperCamelCase__      :					List[Any]=2  ,						UpperCamelCase__      :					Optional[Any]=0.0_2  ,						UpperCamelCase__      :					str=3  ,						UpperCamelCase__      :					int=4  ,						UpperCamelCase__      :					Optional[int]=None  ,						):


       """simple docstring"""







       UpperCamelCase					=  parent
       UpperCamelCase					=  batch_size
       UpperCamelCase					=  seq_length
       UpperCamelCase					=  is_training
       UpperCamelCase					=  use_input_mask
       UpperCamelCase					=  use_token_type_ids
       UpperCamelCase					=  use_labels
       UpperCamelCase					=  vocab_size
       UpperCamelCase					=  hidden_size
       UpperCamelCase					=  num_hidden_layers
       UpperCamelCase					=  num_attention_heads
       UpperCamelCase					=  intermediate_size
       UpperCamelCase					=  hidden_act
       UpperCamelCase					=  hidden_dropout_prob
       UpperCamelCase					=  attention_probs_dropout_prob
       UpperCamelCase					=  max_position_embeddings
       UpperCamelCase					=  type_vocab_size
       UpperCamelCase					=  type_sequence_label_size
       UpperCamelCase					=  initializer_range
       UpperCamelCase					=  num_labels
       UpperCamelCase					=  num_choices
       UpperCamelCase					=  scope






    def  A       (  self      :					str ):


       """simple docstring"""







       UpperCamelCase					=  ids_tensor([self.batch_size, self.seq_length]  ,						self.vocab_size )

       UpperCamelCase					=  None
       if self.use_input_mask:
          UpperCamelCase					=  random_attention_mask([self.batch_size, self.seq_length] )

       UpperCamelCase					=  None
       UpperCamelCase					=  None
       UpperCamelCase					=  None
       if self.use_labels:
          UpperCamelCase					=  ids_tensor([self.batch_size]  ,						self.type_sequence_label_size )
          UpperCamelCase					=  ids_tensor([self.batch_size, self.seq_length]  ,						self.num_labels )
          UpperCamelCase					=  ids_tensor([self.batch_size]  ,						self.num_choices )

       UpperCamelCase					=  self.get_config()

       return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       return DistilBertConfig(
           vocab_size=self.vocab_size  ,						dim=self.hidden_size  ,						n_layers=self.num_hidden_layers  ,						n_heads=self.num_attention_heads  ,						hidden_dim=self.intermediate_size  ,						hidden_act=self.hidden_act  ,						dropout=self.hidden_dropout_prob  ,						attention_dropout=self.attention_probs_dropout_prob  ,						max_position_embeddings=self.max_position_embeddings  ,						initializer_range=self.initializer_range  ,						)






    def  A       (  self      :					Dict  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  DistilBertModel(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						UpperCamelCase__ )
       UpperCamelCase					=  model(UpperCamelCase__ )
       self.parent.assertEqual(result.last_hidden_state.shape  ,						(self.batch_size, self.seq_length, self.hidden_size) )






    def  A       (  self      :					List[Any]  ,						UpperCamelCase__      :					List[str]  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Optional[Any]  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  DistilBertForMaskedLM(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.seq_length, self.vocab_size) )






    def  A       (  self      :					Tuple  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					Optional[Any]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					List[Any] ):


       """simple docstring"""







       UpperCamelCase					=  DistilBertForQuestionAnswering(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(
           UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						start_positions=UpperCamelCase__  ,						end_positions=UpperCamelCase__ )
       self.parent.assertEqual(result.start_logits.shape  ,						(self.batch_size, self.seq_length) )
       self.parent.assertEqual(result.end_logits.shape  ,						(self.batch_size, self.seq_length) )






    def  A       (  self      :					Union[str, Any]  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					int ):


       """simple docstring"""







       UpperCamelCase					=  self.num_labels
       UpperCamelCase					=  DistilBertForSequenceClassification(UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.num_labels) )






    def  A       (  self      :					List[Any]  ,						UpperCamelCase__      :					List[str]  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Optional[int] ):


       """simple docstring"""







       UpperCamelCase					=  self.num_labels
       UpperCamelCase					=  DistilBertForTokenClassification(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()

       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.seq_length, self.num_labels) )






    def  A       (  self      :					List[Any]  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Optional[Any]  ,						UpperCamelCase__      :					Union[str, Any] ):


       """simple docstring"""







       UpperCamelCase					=  self.num_choices
       UpperCamelCase					=  DistilBertForMultipleChoice(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  input_ids.unsqueeze(1 ).expand(-1  ,						self.num_choices  ,						-1 ).contiguous()
       UpperCamelCase					=  input_mask.unsqueeze(1 ).expand(-1  ,						self.num_choices  ,						-1 ).contiguous()
       UpperCamelCase					=  model(
           UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						labels=UpperCamelCase__  ,						)
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.num_choices) )






    def  A       (  self      :					Optional[int] ):


       """simple docstring"""







       UpperCamelCase					=  self.prepare_config_and_inputs()
       ((UpperCamelCase)				,      (UpperCamelCase)				,      (UpperCamelCase)				,      (UpperCamelCase)				,      (UpperCamelCase)				,      (UpperCamelCase))					=  config_and_inputs
       UpperCamelCase					=  {'input_ids': input_ids, 'attention_mask': input_mask}
       return config, inputs_dict

@require_torch
class  SCREAMING_SNAKE_CASE (  _a   ,						_a   ,						unittest.TestCase		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  (
        (
            DistilBertModel,
            DistilBertForMaskedLM,
            DistilBertForMultipleChoice,
            DistilBertForQuestionAnswering,
            DistilBertForSequenceClassification,
            DistilBertForTokenClassification,
        )
        if is_torch_available()
        else None
    )
    _SCREAMING_SNAKE_CASE	  =  (
        {
            """feature-extraction""": DistilBertModel,
            """fill-mask""": DistilBertForMaskedLM,
            """question-answering""": DistilBertForQuestionAnswering,
            """text-classification""": DistilBertForSequenceClassification,
            """token-classification""": DistilBertForTokenClassification,
            """zero-shot""": DistilBertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    _SCREAMING_SNAKE_CASE	  =  True
    _SCREAMING_SNAKE_CASE	  =  True
    _SCREAMING_SNAKE_CASE	  =  True
    _SCREAMING_SNAKE_CASE	  =  True






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  DistilBertModelTester(self )
       UpperCamelCase					=  ConfigTester(self  ,						config_class=UpperCamelCase__  ,						dim=3_7 )






    def  A       (  self      :					List[str] ):


       """simple docstring"""







       self.config_tester.run_common_tests()






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_model(*UpperCamelCase__ )






    def  A       (  self      :					Optional[Any] ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCamelCase__ )






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCamelCase__ )






    def  A       (  self      :					str ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCamelCase__ )






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


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCamelCase__ )






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


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCamelCase__ )






    @slow
    def  A       (  self      :					Tuple ):


       """simple docstring"""







       for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          UpperCamelCase					=  DistilBertModel.from_pretrained(UpperCamelCase__ )
          self.assertIsNotNone(UpperCamelCase__ )






    @slow
    @require_torch_gpu
    def  A       (  self      :					Optional[Any] ):


       """simple docstring"""







       UpperCamelCase				,      UpperCamelCase					=  self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes:
          # BertForMultipleChoice behaves incorrectly in JIT environments.
          if model_class == DistilBertForMultipleChoice:
             return

          UpperCamelCase					=  True
          UpperCamelCase					=  model_class(config=UpperCamelCase__ )

          UpperCamelCase					=  self._prepare_for_class(UpperCamelCase__  ,						UpperCamelCase__ )
          UpperCamelCase					=  torch.jit.trace(
              UpperCamelCase__  ,						(inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) )

          with tempfile.TemporaryDirectory() as tmp:
             torch.jit.save(UpperCamelCase__  ,						os.path.join(UpperCamelCase__  ,						'traced_model.pt' ) )
             UpperCamelCase					=  torch.jit.load(os.path.join(UpperCamelCase__  ,						'traced_model.pt' )  ,						map_location=UpperCamelCase__ )
             loaded(inputs_dict['input_ids'].to(UpperCamelCase__ )  ,						inputs_dict['attention_mask'].to(UpperCamelCase__ ) )

@require_torch
class  SCREAMING_SNAKE_CASE (  unittest.TestCase		):






    """simple docstring"""





    @slow
    def  A       (  self      :					str ):


       """simple docstring"""







       UpperCamelCase					=  DistilBertModel.from_pretrained('distilbert-base-uncased' )
       UpperCamelCase					=  torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] )
       UpperCamelCase					=  torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
       with torch.no_grad():
          UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__ )[0]
       UpperCamelCase					=  torch.Size((1, 1_1, 7_6_8) )
       self.assertEqual(output.shape  ,						UpperCamelCase__ )
       UpperCamelCase					=  torch.tensor(
           [[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]] )

       self.assertTrue(torch.allclose(output[:, 1:4, 1:4]  ,						UpperCamelCase__  ,						atol=1E-4 ) )





"""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_					)}





