




import unittest

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

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
          OpenAIGPTConfig,
          OpenAIGPTDoubleHeadsModel,
          OpenAIGPTForSequenceClassification,
          OpenAIGPTLMHeadModel,
          OpenAIGPTModel,
      )





class     SCREAMING_SNAKE_CASE__		:
     def __init__(						self	:		int       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		Union[str, Any]=13       ,						__lowerCamelCase	:		List[str]=7       ,						__lowerCamelCase	:		List[Any]=True       ,						__lowerCamelCase	:		Dict=True       ,						__lowerCamelCase	:		List[Any]=True       ,						__lowerCamelCase	:		Dict=99       ,						__lowerCamelCase	:		List[Any]=32       ,						__lowerCamelCase	:		int=5       ,						__lowerCamelCase	:		List[Any]=4       ,						__lowerCamelCase	:		Union[str, Any]=37       ,						__lowerCamelCase	:		Any="gelu"       ,						__lowerCamelCase	:		str=0.1       ,						__lowerCamelCase	:		Union[str, Any]=0.1       ,						__lowerCamelCase	:		List[Any]=5_12       ,						__lowerCamelCase	:		str=16       ,						__lowerCamelCase	:		str=2       ,						__lowerCamelCase	:		Tuple=0.02       ,						__lowerCamelCase	:		Dict=3       ,						__lowerCamelCase	:		Tuple=4       ,						__lowerCamelCase	:		List[Any]=None       ,						):



       """simple docstring"""
       lowerCAmelCase__										=      parent
       lowerCAmelCase__										=      batch_size
       lowerCAmelCase__										=      seq_length
       lowerCAmelCase__										=      is_training
       lowerCAmelCase__										=      use_token_type_ids
       lowerCAmelCase__										=      use_labels
       lowerCAmelCase__										=      vocab_size
       lowerCAmelCase__										=      hidden_size
       lowerCAmelCase__										=      num_hidden_layers
       lowerCAmelCase__										=      num_attention_heads
       lowerCAmelCase__										=      intermediate_size
       lowerCAmelCase__										=      hidden_act
       lowerCAmelCase__										=      hidden_dropout_prob
       lowerCAmelCase__										=      attention_probs_dropout_prob
       lowerCAmelCase__										=      max_position_embeddings
       lowerCAmelCase__										=      type_vocab_size
       lowerCAmelCase__										=      type_sequence_label_size
       lowerCAmelCase__										=      initializer_range
       lowerCAmelCase__										=      num_labels
       lowerCAmelCase__										=      num_choices
       lowerCAmelCase__										=      scope
       lowerCAmelCase__										=      self.vocab_size - 1
     def        A__      (						self	:		Tuple						):



       """simple docstring"""
       lowerCAmelCase__										=      ids_tensor([self.batch_size, self.seq_length]       ,						self.vocab_size						)

       lowerCAmelCase__										=      None
       if self.use_token_type_ids:
         lowerCAmelCase__										=      ids_tensor([self.batch_size, self.seq_length]       ,						self.type_vocab_size						)

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

       lowerCAmelCase__										=      OpenAIGPTConfig(
           vocab_size=self.vocab_size       ,						n_embd=self.hidden_size       ,						n_layer=self.num_hidden_layers       ,						n_head=self.num_attention_heads       ,						n_positions=self.max_position_embeddings       ,						pad_token_id=self.pad_token_id       ,						)

       lowerCAmelCase__										=      ids_tensor([self.num_hidden_layers, self.num_attention_heads]       ,						2						)

       return (
           config,
           input_ids,
           head_mask,
           token_type_ids,
           sequence_labels,
           token_labels,
           choice_labels,
       )
     def        A__      (						self	:		int       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		Any       ,						*__lowerCamelCase	:		List[str]						):



       """simple docstring"""
       lowerCAmelCase__										=      OpenAIGPTModel(config=__lowerCamelCase						)
       model.to(__lowerCamelCase						)
       model.eval()

       lowerCAmelCase__										=      model(__lowerCamelCase       ,						token_type_ids=__lowerCamelCase       ,						head_mask=__lowerCamelCase						)
       lowerCAmelCase__										=      model(__lowerCamelCase       ,						token_type_ids=__lowerCamelCase						)
       lowerCAmelCase__										=      model(__lowerCamelCase						)

       self.parent.assertEqual(result.last_hidden_state.shape       ,						(self.batch_size, self.seq_length, self.hidden_size)						)
     def        A__      (						self	:		int       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		List[str]       ,						*__lowerCamelCase	:		int						):



       """simple docstring"""
       lowerCAmelCase__										=      OpenAIGPTLMHeadModel(__lowerCamelCase						)
       model.to(__lowerCamelCase						)
       model.eval()

       lowerCAmelCase__										=      model(__lowerCamelCase       ,						token_type_ids=__lowerCamelCase       ,						labels=__lowerCamelCase						)
       self.parent.assertEqual(result.loss.shape       ,						()						)
       self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.seq_length, self.vocab_size)						)
     def        A__      (						self	:		Tuple       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		Any       ,						__lowerCamelCase	:		Union[str, Any]       ,						__lowerCamelCase	:		Any       ,						*__lowerCamelCase	:		List[Any]						):



       """simple docstring"""
       lowerCAmelCase__										=      OpenAIGPTDoubleHeadsModel(__lowerCamelCase						)
       model.to(__lowerCamelCase						)
       model.eval()

       lowerCAmelCase__										=      model(__lowerCamelCase       ,						token_type_ids=__lowerCamelCase       ,						labels=__lowerCamelCase						)
       self.parent.assertEqual(result.loss.shape       ,						()						)
       self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.seq_length, self.vocab_size)						)
     def        A__      (						self	:		Dict       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		Dict       ,						*__lowerCamelCase	:		Any						):



       """simple docstring"""
       lowerCAmelCase__										=      self.num_labels
       lowerCAmelCase__										=      OpenAIGPTForSequenceClassification(__lowerCamelCase						)
       model.to(__lowerCamelCase						)
       model.eval()

       lowerCAmelCase__										=      ids_tensor([self.batch_size]       ,						self.type_sequence_label_size						)
       lowerCAmelCase__										=      model(__lowerCamelCase       ,						token_type_ids=__lowerCamelCase       ,						labels=__lowerCamelCase						)
       self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.num_labels)						)



     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       lowerCAmelCase__										=      self.prepare_config_and_inputs()
       (
           (
           lowerCAmelCase__
       )				,      (
           lowerCAmelCase__
       )				,      (
           lowerCAmelCase__
       )				,      (
           lowerCAmelCase__
       )				,      (
           lowerCAmelCase__
       )				,      (
           lowerCAmelCase__
       )				,      (
           lowerCAmelCase__
       )				,      
       )										=      config_and_inputs
       lowerCAmelCase__										=      {
           '''input_ids''': input_ids,
           '''token_type_ids''': token_type_ids,
           '''head_mask''': head_mask,
       }

       return config, inputs_dict





@require_torch
class     SCREAMING_SNAKE_CASE__		(_a    ,					_a    ,					_a    ,					unittest.TestCase			):
     lowercase_ :      str				= (
         (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
         if is_torch_available()
         else ()
     )
     lowercase_ :      Tuple				= (
         (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
     )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
     lowercase_ :      Tuple				= (
         {
             "feature-extraction": OpenAIGPTModel,
             "text-classification": OpenAIGPTForSequenceClassification,
             "text-generation": OpenAIGPTLMHeadModel,
             "zero-shot": OpenAIGPTForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     def        A__      (						self	:		List[str]       ,						__lowerCamelCase	:		Any       ,						__lowerCamelCase	:		Any       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		Any       ,						__lowerCamelCase	:		Dict						):



       """simple docstring"""
       if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
         # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
         # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
         # tiny config could not be created.
         return True

       return False
     def        A__      (						self	:		str       ,						__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		Optional[Any]=False						):



       """simple docstring"""
       lowerCAmelCase__										=      super()._prepare_for_class(__lowerCamelCase       ,						__lowerCamelCase       ,						return_labels=__lowerCamelCase						)

       if return_labels:
         if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
           lowerCAmelCase__										=      torch.zeros(
               (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)       ,						dtype=torch.long       ,						device=__lowerCamelCase       ,						)
           lowerCAmelCase__										=      inputs_dict['''labels''']
           lowerCAmelCase__										=      inputs_dict['''labels''']
           lowerCAmelCase__										=      torch.zeros(
               (self.model_tester.batch_size, self.model_tester.num_choices)       ,						dtype=torch.long       ,						device=__lowerCamelCase       ,						)
           lowerCAmelCase__										=      torch.zeros(
               self.model_tester.batch_size       ,						dtype=torch.long       ,						device=__lowerCamelCase						)
       return inputs_dict
     def        A__      (						self	:		Dict						):



       """simple docstring"""
       lowerCAmelCase__										=      OpenAIGPTModelTester(self						)
       lowerCAmelCase__										=      ConfigTester(self       ,						config_class=__lowerCamelCase       ,						n_embd=37						)
     def        A__      (						self	:		Optional[Any]						):



       """simple docstring"""
       self.config_tester.run_common_tests()
     def        A__      (						self	:		Tuple						):



       """simple docstring"""
       lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_model(*__lowerCamelCase						)
     def        A__      (						self	:		Union[str, Any]						):



       """simple docstring"""
       lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_lm_head_model(*__lowerCamelCase						)
     def        A__      (						self	:		Any						):



       """simple docstring"""
       lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_double_lm_head_model(*__lowerCamelCase						)
     def        A__      (						self	:		int						):



       """simple docstring"""
       lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__lowerCamelCase						)



     @slow
     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__										=      OpenAIGPTModel.from_pretrained(__lowerCamelCase						)
         self.assertIsNotNone(__lowerCamelCase						)





@require_torch
class     SCREAMING_SNAKE_CASE__		(unittest.TestCase			):
     @slow
     def        A__      (						self	:		Optional[Any]						):



       """simple docstring"""
       lowerCAmelCase__										=      OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''						)
       model.to(__lowerCamelCase						)
       lowerCAmelCase__										=      torch.tensor([[4_81, 47_35, 5_44]]       ,						dtype=torch.long       ,						device=__lowerCamelCase						)  # the president is
       lowerCAmelCase__										=      [
           4_81,
           47_35,
           5_44,
           2_46,
           9_63,
           8_70,
           7_62,
           2_39,
           2_44,
           4_04_77,
           2_44,
           2_49,
           7_19,
           8_81,
           4_87,
           5_44,
           2_40,
           2_44,
           6_03,
           4_81,
       ]  # the president is a very good man. " \n " i\'m sure he is, " said the

       lowerCAmelCase__										=      model.generate(__lowerCamelCase       ,						do_sample=__lowerCamelCase						)
       self.assertListEqual(output_ids[0].tolist()       ,						__lowerCamelCase						)







from scipy.stats import pearsonr

import datasets


__magic_name__  :  Union[str, Any]					=       """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""


__magic_name__  :  Tuple					=       """
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


__magic_name__  :  int					=       """
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,					_KWARGS_DESCRIPTION			)
class     SCREAMING_SNAKE_CASE__		(datasets.Metric			):
     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       return datasets.MetricInfo(
           description=_DESCRIPTION       ,						citation=_CITATION       ,						inputs_description=_KWARGS_DESCRIPTION       ,						features=datasets.Features(
               {
                   '''predictions''': datasets.Value('''float'''						),
                   '''references''': datasets.Value('''float'''						),
               }						)       ,						reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html''']       ,						)



     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		Tuple       ,						__lowerCamelCase	:		Dict=False						):



       """simple docstring"""
       if return_pvalue:
         lowerCAmelCase__										=      pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)
         return {"pearsonr": results[0], "p-value": results[1]}
       else:
         return {"pearsonr": float(pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)[0]						)}

