


import gc
import unittest

from transformers import CTRLConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
       CTRLForSequenceClassification,
       CTRLLMHeadModel,
       CTRLModel,
   )



class        a					:





     def __init__(    self					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=14    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]=7    ,	SCREAMING_SNAKE_CASE_					:				Any=True    ,	SCREAMING_SNAKE_CASE_					:				Tuple=True    ,	SCREAMING_SNAKE_CASE_					:				str=True    ,	SCREAMING_SNAKE_CASE_					:				Dict=True    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]=True    ,	SCREAMING_SNAKE_CASE_					:				Tuple=99    ,	SCREAMING_SNAKE_CASE_					:				Any=32    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]=5    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]=4    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=37    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]="gelu"    ,	SCREAMING_SNAKE_CASE_					:				List[str]=0.1    ,	SCREAMING_SNAKE_CASE_					:				Dict=0.1    ,	SCREAMING_SNAKE_CASE_					:				int=512    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]=16    ,	SCREAMING_SNAKE_CASE_					:				str=2    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]=0.02    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=3    ,	SCREAMING_SNAKE_CASE_					:				str=4    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=None    ,	):
        __lowerCamelCase:				Dict     =	parent
        __lowerCamelCase:				Dict     =	batch_size
        __lowerCamelCase:				List[str]     =	seq_length
        __lowerCamelCase:				Optional[Any]     =	is_training
        __lowerCamelCase:				List[str]     =	use_token_type_ids
        __lowerCamelCase:				Union[str, Any]     =	use_input_mask
        __lowerCamelCase:				Union[str, Any]     =	use_labels
        __lowerCamelCase:				List[str]     =	use_mc_token_ids
        __lowerCamelCase:				List[str]     =	vocab_size
        __lowerCamelCase:				Any     =	hidden_size
        __lowerCamelCase:				int     =	num_hidden_layers
        __lowerCamelCase:				str     =	num_attention_heads
        __lowerCamelCase:				Any     =	intermediate_size
        __lowerCamelCase:				Optional[Any]     =	hidden_act
        __lowerCamelCase:				Dict     =	hidden_dropout_prob
        __lowerCamelCase:				Optional[int]     =	attention_probs_dropout_prob
        __lowerCamelCase:				Any     =	max_position_embeddings
        __lowerCamelCase:				Any     =	type_vocab_size
        __lowerCamelCase:				Optional[Any]     =	type_sequence_label_size
        __lowerCamelCase:				str     =	initializer_range
        __lowerCamelCase:				Optional[Any]     =	num_labels
        __lowerCamelCase:				List[str]     =	num_choices
        __lowerCamelCase:				List[str]     =	scope
        __lowerCamelCase:				Dict     =	self.vocab_size - 1





     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict							):
        __lowerCamelCase:				Optional[int]     =	ids_tensor([self.batch_size, self.seq_length]    ,	self.vocab_size							)

        __lowerCamelCase:				Optional[int]     =	None
        if self.use_input_mask:
           __lowerCamelCase:				Dict     =	random_attention_mask([self.batch_size, self.seq_length]							)

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

        __lowerCamelCase:				Dict     =	None
        if self.use_mc_token_ids:
           __lowerCamelCase:				Dict     =	ids_tensor([self.batch_size, self.num_choices]    ,	self.seq_length							)

        __lowerCamelCase:				int     =	None
        __lowerCamelCase:				int     =	None
        __lowerCamelCase:				Tuple     =	None
        if self.use_labels:
           __lowerCamelCase:				Optional[Any]     =	ids_tensor([self.batch_size]    ,	self.type_sequence_label_size							)
           __lowerCamelCase:				List[Any]     =	ids_tensor([self.batch_size, self.seq_length]    ,	self.num_labels							)
           __lowerCamelCase:				Optional[int]     =	ids_tensor([self.batch_size]    ,	self.num_choices							)

        __lowerCamelCase:				Tuple     =	self.get_config()

        __lowerCamelCase:				Dict     =	ids_tensor([self.num_hidden_layers, self.num_attention_heads]    ,	2							)

        return (
            config,
            input_ids,
            input_mask,
            head_mask,
            token_type_ids,
            mc_token_ids,
            sequence_labels,
            token_labels,
            choice_labels,
        )





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        return CTRLConfig(
            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    ,	)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	*SCREAMING_SNAKE_CASE_					:				Optional[int]							):
        __lowerCamelCase:				Any     =	CTRLModel(config=SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()

        model(SCREAMING_SNAKE_CASE_    ,	token_type_ids=SCREAMING_SNAKE_CASE_    ,	head_mask=SCREAMING_SNAKE_CASE_							)
        model(SCREAMING_SNAKE_CASE_    ,	token_type_ids=SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Union[str, Any]     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.last_hidden_state.shape    ,	(self.batch_size, self.seq_length, self.hidden_size)							)
        self.parent.assertEqual(len(result.past_key_values							)    ,	config.n_layer							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				int    ,	SCREAMING_SNAKE_CASE_					:				str    ,	*SCREAMING_SNAKE_CASE_					:				List[Any]							):
        __lowerCamelCase:				Dict     =	CTRLLMHeadModel(SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()

        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_    ,	token_type_ids=SCREAMING_SNAKE_CASE_    ,	labels=SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.loss.shape    ,	()							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.seq_length, self.vocab_size)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        __lowerCamelCase:				str     =	self.prepare_config_and_inputs()

        (
            (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     (
            __lowerCamelCase
        )   ,     
        ):				Optional[Any]     =	config_and_inputs

        __lowerCamelCase:				Optional[int]     =	{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

        return config, inputs_dict







     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	*SCREAMING_SNAKE_CASE_					:				List[Any]							):
        __lowerCamelCase:				Union[str, Any]     =	self.num_labels
        __lowerCamelCase:				int     =	CTRLForSequenceClassification(SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()
        __lowerCamelCase:				int     =	ids_tensor([self.batch_size]    ,	self.type_sequence_label_size							)
        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_    ,	token_type_ids=SCREAMING_SNAKE_CASE_    ,	labels=SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.num_labels)							)



@require_torch
class        a					(			_UpperCAmelCase     ,_UpperCAmelCase     ,_UpperCAmelCase     ,unittest.TestCase   ):
     UpperCAmelCase__ :  str						      =	(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
     UpperCAmelCase__ :  Union[str, Any]						      =	(CTRLLMHeadModel,) if is_torch_available() else ()
     UpperCAmelCase__ :  Union[str, Any]						      =	(
         {
             "feature-extraction": CTRLModel,
             "text-classification": CTRLForSequenceClassification,
             "text-generation": CTRLLMHeadModel,
             "zero-shot": CTRLForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     UpperCAmelCase__ :  Optional[int]						      =	True
     UpperCAmelCase__ :  Dict						      =	False
     UpperCAmelCase__ :  str						      =	False





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				Tuple							):
        if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
           # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
           # `CTRLConfig` 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  SCREAMING_SNAKE_CASE__       (    self					:				Tuple							):
        __lowerCamelCase:				Tuple     =	CTRLModelTester(self							)
        __lowerCamelCase:				Dict     =	ConfigTester(self    ,	config_class=SCREAMING_SNAKE_CASE_    ,	n_embd=37							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        super().tearDown()
        # clean-up as much as possible GPU memory occupied by PyTorch
        gc.collect()
        torch.cuda.empty_cache()





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        self.config_tester.run_common_tests()





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]							):
        __lowerCamelCase:				int     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_model(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Tuple							):
        __lowerCamelCase:				List[Any]     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE_							)





     @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""							)
     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict							):
        pass





     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				Tuple							):
        for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:				List[str]     =	CTRLModel.from_pretrained(SCREAMING_SNAKE_CASE_							)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_							)







     @unittest.skip("""The model doesn't support left padding"""							)  # and it's not used enough to be worth fixing :)
     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]							):
        pass



@require_torch
class        a					(			unittest.TestCase   ):





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        super().tearDown()
        # clean-up as much as possible GPU memory occupied by PyTorch
        gc.collect()
        torch.cuda.empty_cache()







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        __lowerCamelCase:				Dict     =	CTRLLMHeadModel.from_pretrained("""ctrl"""							)
        model.to(SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Any     =	torch.tensor(
            [[11859, 0, 1611, 8]]    ,	dtype=torch.long    ,	device=SCREAMING_SNAKE_CASE_							)  # Legal the president is
        __lowerCamelCase:				int     =	[
            11859,
            0,
            1611,
            8,
            5,
            150,
            26449,
            2,
            19,
            348,
            469,
            3,
            2595,
            48,
            20740,
            246533,
            246533,
            19,
            30,
            5,
        ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

        __lowerCamelCase:				Optional[Any]     =	model.generate(SCREAMING_SNAKE_CASE_    ,	do_sample=SCREAMING_SNAKE_CASE_							)
        self.assertListEqual(output_ids[0].tolist()    ,	SCREAMING_SNAKE_CASE_							)






from sklearn.metrics import fa_score

import datasets


_A		:				Any									=       '''
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)
'''


_A		:				Dict									=       '''
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. ])}
'''


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





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, 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  SCREAMING_SNAKE_CASE__       (    self					:				int    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				str    ,	SCREAMING_SNAKE_CASE_					:				str=None    ,	SCREAMING_SNAKE_CASE_					:				str=1    ,	SCREAMING_SNAKE_CASE_					:				List[str]="binary"    ,	SCREAMING_SNAKE_CASE_					:				List[str]=None							):
        __lowerCamelCase:				str     =	fa_score(
            SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	labels=SCREAMING_SNAKE_CASE_    ,	pos_label=SCREAMING_SNAKE_CASE_    ,	average=SCREAMING_SNAKE_CASE_    ,	sample_weight=SCREAMING_SNAKE_CASE_							)
        return {"f1": float(SCREAMING_SNAKE_CASE_							) if score.size == 1 else score}


