




'''simple docstring'''







from sklearn.metrics import fa_score

import datasets


A									='\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n'


A									='\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    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.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    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\'`.\n\n        - \'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.\n        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - \'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.\n        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    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.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> f1_metric = datasets.load_metric("f1")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {\'f1\': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> f1_metric = datasets.load_metric("f1")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results[\'f1\'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> f1_metric = datasets.load_metric("f1")\n        >>> 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])\n        >>> print(round(results[\'f1\'], 2))\n        0.35\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n        >>> print(round(results[\'f1\'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n        >>> print(round(results[\'f1\'], 2))\n        0.33\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n        >>> print(round(results[\'f1\'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {\'f1\': array([0.8, 0. , 0. ])}\n'


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


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,							_KWARGS_DESCRIPTION				)
class     _a						(			datasets.Metric				):
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           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 					A   (			self		:			Optional[int]     ,       lowercase		:			Optional[Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[int]=None     ,       lowercase		:			Optional[int]=1     ,       lowercase		:			str="binary"     ,       lowercase		:			Optional[int]=None       ):



           '''simple docstring'''

           UpperCAmelCase     =	fa_score(
               lowercase     ,       lowercase     ,       labels=lowercase     ,       pos_label=lowercase     ,       average=lowercase     ,       sample_weight=lowercase       )
           return {"f1": float(lowercase       ) if score.size == 1 else score}










'''simple docstring'''







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     _a						:
       def __init__(			self		:			Optional[Any]     ,       lowercase		:			int     ,       lowercase		:			str=13     ,       lowercase		:			int=7     ,       lowercase		:			Optional[int]=True     ,       lowercase		:			Dict=True     ,       lowercase		:			Union[str, Any]=True     ,       lowercase		:			Union[str, Any]=99     ,       lowercase		:			Optional[Any]=32     ,       lowercase		:			List[Any]=5     ,       lowercase		:			List[Any]=4     ,       lowercase		:			int=37     ,       lowercase		:			int="gelu"     ,       lowercase		:			Tuple=0.1     ,       lowercase		:			Dict=0.1     ,       lowercase		:			Tuple=512     ,       lowercase		:			List[str]=16     ,       lowercase		:			Optional[int]=2     ,       lowercase		:			int=0.02     ,       lowercase		:			str=3     ,       lowercase		:			List[Any]=4     ,       lowercase		:			List[str]=None     ,       ):



           '''simple docstring'''

           UpperCAmelCase     =	parent
           UpperCAmelCase     =	batch_size
           UpperCAmelCase     =	seq_length
           UpperCAmelCase     =	is_training
           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
           UpperCAmelCase     =	self.vocab_size - 1
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

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

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

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

           UpperCAmelCase     =	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		:			Any     ,       lowercase		:			Tuple     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[Any]     ,       lowercase		:			List[str]     ,       *lowercase		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTModel(config=lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       head_mask=lowercase       )
           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase       )
           UpperCAmelCase     =	model(lowercase       )

           self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.seq_length, self.hidden_size)       )
       def 					A   (			self		:			List[str]     ,       lowercase		:			Optional[int]     ,       lowercase		:			List[Any]     ,       lowercase		:			str     ,       lowercase		:			Optional[int]     ,       *lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTLMHeadModel(lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           self.parent.assertEqual(result.loss.shape     ,       ()       )
           self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.seq_length, self.vocab_size)       )
       def 					A   (			self		:			Optional[int]     ,       lowercase		:			Tuple     ,       lowercase		:			Tuple     ,       lowercase		:			Optional[int]     ,       lowercase		:			Optional[int]     ,       *lowercase		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTDoubleHeadsModel(lowercase       )
           model.to(lowercase       )
           model.eval()

           UpperCAmelCase     =	model(lowercase     ,       token_type_ids=lowercase     ,       labels=lowercase       )
           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     ,       lowercase		:			Dict     ,       lowercase		:			Any     ,       lowercase		:			Any     ,       lowercase		:			Optional[int]     ,       *lowercase		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.num_labels
           UpperCAmelCase     =	OpenAIGPTForSequenceClassification(lowercase       )
           model.to(lowercase       )
           model.eval()

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







       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.prepare_config_and_inputs()
           (
               (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  (
               UpperCAmelCase
           ) ,  
           )     =	config_and_inputs
           UpperCAmelCase     =	{
               '''input_ids''': input_ids,
               '''token_type_ids''': token_type_ids,
               '''head_mask''': head_mask,
           }

           return config, inputs_dict






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



           '''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		:			List[Any]     ,       lowercase		:			int     ,       lowercase		:			List[Any]     ,       lowercase		:			Optional[Any]=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	super()._prepare_for_class(lowercase     ,       lowercase     ,       return_labels=lowercase       )

           if return_labels:
               if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                   UpperCAmelCase     =	torch.zeros(
                       (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)     ,       dtype=torch.long     ,       device=lowercase     ,       )
                   UpperCAmelCase     =	inputs_dict['''labels''']
                   UpperCAmelCase     =	inputs_dict['''labels''']
                   UpperCAmelCase     =	torch.zeros(
                       (self.model_tester.batch_size, self.model_tester.num_choices)     ,       dtype=torch.long     ,       device=lowercase     ,       )
                   UpperCAmelCase     =	torch.zeros(
                       self.model_tester.batch_size     ,       dtype=torch.long     ,       device=lowercase       )
           return inputs_dict
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTModelTester(self       )
           UpperCAmelCase     =	ConfigTester(self     ,       config_class=lowercase     ,       n_embd=37       )
       def 					A   (			self		:			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_openai_gpt_model(*lowercase       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_lm_head_model(*lowercase       )
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_double_lm_head_model(*lowercase       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowercase       )







       @slow
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase     =	OpenAIGPTModel.from_pretrained(lowercase       )
               self.assertIsNotNone(lowercase       )






@require_torch
class     _a						(			unittest.TestCase				):
       @slow
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''       )
           model.to(lowercase       )
           UpperCAmelCase     =	torch.tensor([[481, 4_735, 544]]     ,       dtype=torch.long     ,       device=lowercase       )  # the president is
           UpperCAmelCase     =	[
               481,
               4_735,
               544,
               246,
               963,
               870,
               762,
               239,
               244,
               40_477,
               244,
               249,
               719,
               881,
               487,
               544,
               240,
               244,
               603,
               481,
           ]  # the president is a very good man. " \n " i\'m sure he is, " said the

           UpperCAmelCase     =	model.generate(lowercase     ,       do_sample=lowercase       )
           self.assertListEqual(output_ids[0].tolist()     ,       lowercase       )




