


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  snake_case_     :
					def __init__(   self     :Union[str, Any]    ,__snake_case     :Optional[Any]    ,__snake_case     :Dict=13    ,__snake_case     :str=7    ,__snake_case     :Any=True    ,__snake_case     :Tuple=True    ,__snake_case     :Tuple=True    ,__snake_case     :Dict=99    ,__snake_case     :List[Any]=32    ,__snake_case     :int=5    ,__snake_case     :Optional[int]=4    ,__snake_case     :Tuple=37    ,__snake_case     :Dict="gelu"    ,__snake_case     :List[Any]=0.1    ,__snake_case     :Optional[int]=0.1    ,__snake_case     :Any=5_12    ,__snake_case     :Dict=16    ,__snake_case     :Tuple=2    ,__snake_case     :List[Any]=0.02    ,__snake_case     :Tuple=3    ,__snake_case     :List[str]=4    ,__snake_case     :Optional[Any]=None    ,)      ->					str:
												a__    =  parent
												a__    =  batch_size
												a__    =  seq_length
												a__    =  is_training
												a__    =  use_token_type_ids
												a__    =  use_labels
												a__    =  vocab_size
												a__    =  hidden_size
												a__    =  num_hidden_layers
												a__    =  num_attention_heads
												a__    =  intermediate_size
												a__    =  hidden_act
												a__    =  hidden_dropout_prob
												a__    =  attention_probs_dropout_prob
												a__    =  max_position_embeddings
												a__    =  type_vocab_size
												a__    =  type_sequence_label_size
												a__    =  initializer_range
												a__    =  num_labels
												a__    =  num_choices
												a__    =  scope
												a__    =  self.vocab_size - 1
					def 				lowerCamelCase__(   self     :Any   )      ->					Dict:
												a__    =  ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size   )

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

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

												a__    =  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    ,)

												a__    =  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 				lowerCamelCase__(   self     :List[str]    ,__snake_case     :Optional[Any]    ,__snake_case     :Optional[int]    ,__snake_case     :Optional[int]    ,__snake_case     :Union[str, Any]    ,*__snake_case     :Tuple   )      ->					Tuple:
												a__    =  OpenAIGPTModel(config=__snake_case   )
												model.to(__snake_case   )
												model.eval()

												a__    =  model(__snake_case    ,token_type_ids=__snake_case    ,head_mask=__snake_case   )
												a__    =  model(__snake_case    ,token_type_ids=__snake_case   )
												a__    =  model(__snake_case   )

												self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)   )
					def 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :Optional[Any]    ,__snake_case     :int    ,__snake_case     :Any    ,__snake_case     :List[Any]    ,*__snake_case     :int   )      ->					Dict:
												a__    =  OpenAIGPTLMHeadModel(__snake_case   )
												model.to(__snake_case   )
												model.eval()

												a__    =  model(__snake_case    ,token_type_ids=__snake_case    ,labels=__snake_case   )
												self.parent.assertEqual(result.loss.shape    ,()   )
												self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)   )
					def 				lowerCamelCase__(   self     :List[Any]    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :int    ,*__snake_case     :Union[str, Any]   )      ->					int:
												a__    =  OpenAIGPTDoubleHeadsModel(__snake_case   )
												model.to(__snake_case   )
												model.eval()

												a__    =  model(__snake_case    ,token_type_ids=__snake_case    ,labels=__snake_case   )
												self.parent.assertEqual(result.loss.shape    ,()   )
												self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)   )
					def 				lowerCamelCase__(   self     :Tuple    ,__snake_case     :Optional[Any]    ,__snake_case     :Any    ,__snake_case     :Tuple    ,__snake_case     :List[Any]    ,*__snake_case     :List[Any]   )      ->					Dict:
												a__    =  self.num_labels
												a__    =  OpenAIGPTForSequenceClassification(__snake_case   )
												model.to(__snake_case   )
												model.eval()

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



					def 				lowerCamelCase__(   self     :Tuple   )      ->					List[Any]:
												a__    =  self.prepare_config_and_inputs()
												(
												    a__
												)    =  config_and_inputs
												a__    =  {
												    """input_ids""": input_ids,
												    """token_type_ids""": token_type_ids,
												    """head_mask""": head_mask,
												}

												return config, inputs_dict







@require_torch
class  snake_case_     (A_			,		A_			,		A_			,		unittest.TestCase   ):
					UpperCAmelCase__      :					Dict					   =    (
					    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
					    if is_torch_available()
					    else ()
					)
					UpperCAmelCase__      :					Dict					   =    (
					    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
					)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
					UpperCAmelCase__      :					List[Any]					   =    (
					    {
					        '''feature-extraction''': OpenAIGPTModel,
					        '''text-classification''': OpenAIGPTForSequenceClassification,
					        '''text-generation''': OpenAIGPTLMHeadModel,
					        '''zero-shot''': OpenAIGPTForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					def 				lowerCamelCase__(   self     :int    ,__snake_case     :Tuple    ,__snake_case     :int    ,__snake_case     :str    ,__snake_case     :List[Any]    ,__snake_case     :int   )      ->					Any:
												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 				lowerCamelCase__(   self     :str    ,__snake_case     :Optional[int]    ,__snake_case     :List[Any]    ,__snake_case     :List[Any]=False   )      ->					List[str]:
												a__    =  super()._prepare_for_class(__snake_case    ,__snake_case    ,return_labels=__snake_case   )

												if return_labels:
																			if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
																										a__    =  torch.zeros(
																										    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)    ,dtype=torch.long    ,device=__snake_case    ,)
																										a__    =  inputs_dict["""labels"""]
																										a__    =  inputs_dict["""labels"""]
																										a__    =  torch.zeros(
																										    (self.model_tester.batch_size, self.model_tester.num_choices)    ,dtype=torch.long    ,device=__snake_case    ,)
																										a__    =  torch.zeros(
																										    self.model_tester.batch_size    ,dtype=torch.long    ,device=__snake_case   )
												return inputs_dict
					def 				lowerCamelCase__(   self     :Dict   )      ->					str:
												a__    =  OpenAIGPTModelTester(self   )
												a__    =  ConfigTester(self    ,config_class=__snake_case    ,n_embd=37   )
					def 				lowerCamelCase__(   self     :Dict   )      ->					Optional[Any]:
												self.config_tester.run_common_tests()
					def 				lowerCamelCase__(   self     :str   )      ->					List[str]:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_openai_gpt_model(*__snake_case   )
					def 				lowerCamelCase__(   self     :Optional[int]   )      ->					Dict:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_lm_head_model(*__snake_case   )
					def 				lowerCamelCase__(   self     :List[Any]   )      ->					Dict:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_double_lm_head_model(*__snake_case   )
					def 				lowerCamelCase__(   self     :Any   )      ->					List[Any]:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__snake_case   )



					@slow
					def 				lowerCamelCase__(   self     :Optional[Any]   )      ->					Union[str, Any]:
												for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			a__    =  OpenAIGPTModel.from_pretrained(__snake_case   )
																			self.assertIsNotNone(__snake_case   )







@require_torch
class  snake_case_     (unittest.TestCase   ):
					@slow
					def 				lowerCamelCase__(   self     :Dict   )      ->					Optional[Any]:
												a__    =  OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'   )
												model.to(__snake_case   )
												a__    =  torch.tensor([[4_81, 47_35, 5_44]]    ,dtype=torch.long    ,device=__snake_case   )  # the president is
												a__    =  [
												    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

												a__    =  model.generate(__snake_case    ,do_sample=__snake_case   )
												self.assertListEqual(output_ids[0].tolist()    ,__snake_case   )





from sklearn.metrics import fa_score

import datasets


snake_case							: Optional[int]      =   '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


snake_case							: List[Any]      =   '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'f1\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


snake_case							: Union[str, Any]      =   '''
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,		_KWARGS_DESCRIPTION   )
class  snake_case_     (datasets.Metric   ):
					def 				lowerCamelCase__(   self     :Any   )      ->					Any:
												return datasets.MetricInfo(
												    description=_DESCRIPTION    ,citation=_CITATION    ,inputs_description=_KWARGS_DESCRIPTION    ,features=datasets.Features(
												        {
												            'predictions': datasets.Sequence(datasets.Value('int32'   )   ),
												            'references': datasets.Sequence(datasets.Value('int32'   )   ),
												        }
												        if self.config_name == 'multilabel'
												        else {
												            'predictions': datasets.Value('int32'   ),
												            'references': datasets.Value('int32'   ),
												        }   )    ,reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html']    ,)



					def 				lowerCamelCase__(   self     :Dict    ,__snake_case     :str    ,__snake_case     :str    ,__snake_case     :Dict=None    ,__snake_case     :str=1    ,__snake_case     :Optional[int]="binary"    ,__snake_case     :Union[str, Any]=None   )      ->					Tuple:
												a__    =  fa_score(
												    __snake_case    ,__snake_case    ,labels=__snake_case    ,pos_label=__snake_case    ,average=__snake_case    ,sample_weight=__snake_case   )
												return {"f1": float(__snake_case   ) if score.size == 1 else score}




