




from sklearn.metrics import fa_score

import datasets


lowerCamelCase				:		Any     =   "\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"


lowerCamelCase				:		List[Any]     =   "\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"


lowerCamelCase				:		Tuple     =   "\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   ):



 '''simple docstring'''


 def 				a__ (				self					:  Union[str, Any]  )   ->	Dict:

       """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					:  str						,							A_					:  List[str]						,							A_					:  List[Any]						,							A_					:  str=None						,							A_					:  int=1						,							A_					:  Union[str, Any]="binary"						,							A_					:  int=None  )   ->	Optional[int]:

       """simple docstring"""






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









from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import numpy as np
 import tensorflow as tf

 from transformers import (
     TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
     FlaubertConfig,
     TFFlaubertForMultipleChoice,
     TFFlaubertForQuestionAnsweringSimple,
     TFFlaubertForSequenceClassification,
     TFFlaubertForTokenClassification,
     TFFlaubertModel,
     TFFlaubertWithLMHeadModel,
 )







class   A:



 '''simple docstring'''


 def __init__(				self					:  str						,							A_					:  Optional[Any]						,							)   ->	str:

       """simple docstring"""






       lowerCamelCase_		     =    parent
       lowerCamelCase_		     =    13
       lowerCamelCase_		     =    7
       lowerCamelCase_		     =    True
       lowerCamelCase_		     =    True
       lowerCamelCase_		     =    True
       lowerCamelCase_		     =    True
       lowerCamelCase_		     =    True
       lowerCamelCase_		     =    False
       lowerCamelCase_		     =    False
       lowerCamelCase_		     =    False
       lowerCamelCase_		     =    2
       lowerCamelCase_		     =    99
       lowerCamelCase_		     =    0
       lowerCamelCase_		     =    32
       lowerCamelCase_		     =    2
       lowerCamelCase_		     =    4
       lowerCamelCase_		     =    0.1
       lowerCamelCase_		     =    0.1
       lowerCamelCase_		     =    512
       lowerCamelCase_		     =    16
       lowerCamelCase_		     =    2
       lowerCamelCase_		     =    0.02
       lowerCamelCase_		     =    3
       lowerCamelCase_		     =    4
       lowerCamelCase_		     =    'last'
       lowerCamelCase_		     =    True
       lowerCamelCase_		     =    None
       lowerCamelCase_		     =    0

 def 				a__ (				self					:  Dict  )   ->	Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_		     =    ids_tensor([self.batch_size, self.seq_length]						,							self.vocab_size  )
       lowerCamelCase_		     =    random_attention_mask([self.batch_size, self.seq_length]						,							dtype=tf.floataa  )

       lowerCamelCase_		     =    None
       if self.use_input_lengths:
             lowerCamelCase_		     =    (
                 ids_tensor([self.batch_size]						,							vocab_size=2  ) + self.seq_length - 2
             )  # small variation of seq_length

       lowerCamelCase_		     =    None
       if self.use_token_type_ids:
             lowerCamelCase_		     =    ids_tensor([self.batch_size, self.seq_length]						,							self.n_langs  )

       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]						,							2						,							dtype=tf.floataa  )
             lowerCamelCase_		     =    ids_tensor([self.batch_size]						,							self.num_choices  )

       lowerCamelCase_		     =    FlaubertConfig(
           vocab_size=self.vocab_size						,							n_special=self.n_special						,							emb_dim=self.hidden_size						,							n_layers=self.num_hidden_layers						,							n_heads=self.num_attention_heads						,							dropout=self.hidden_dropout_prob						,							attention_dropout=self.attention_probs_dropout_prob						,							gelu_activation=self.gelu_activation						,							sinusoidal_embeddings=self.sinusoidal_embeddings						,							asm=self.asm						,							causal=self.causal						,							n_langs=self.n_langs						,							max_position_embeddings=self.max_position_embeddings						,							initializer_range=self.initializer_range						,							summary_type=self.summary_type						,							use_proj=self.use_proj						,							bos_token_id=self.bos_token_id						,							)

       return (
           config,
           input_ids,
           token_type_ids,
           input_lengths,
           sequence_labels,
           token_labels,
           is_impossible_labels,
           choice_labels,
           input_mask,
       )

 def 				a__ (				self					:  int						,							A_					:  List[str]						,							A_					:  List[Any]						,							A_					:  str						,							A_					:  List[Any]						,							A_					:  int						,							A_					:  Tuple						,							A_					:  Optional[int]						,							A_					:  Optional[int]						,							A_					:  str						,							)   ->	Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_		     =    TFFlaubertModel(config=A_  )
       lowerCamelCase_		     =    {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
       lowerCamelCase_		     =    model(A_  )

       lowerCamelCase_		     =    [input_ids, input_mask]
       lowerCamelCase_		     =    model(A_  )
       self.parent.assertEqual(result.last_hidden_state.shape						,							(self.batch_size, self.seq_length, self.hidden_size)  )

 def 				a__ (				self					:  Tuple						,							A_					:  List[str]						,							A_					:  int						,							A_					:  List[Any]						,							A_					:  Any						,							A_					:  Any						,							A_					:  Dict						,							A_					:  str						,							A_					:  List[Any]						,							A_					:  Union[str, Any]						,							)   ->	List[str]:

       """simple docstring"""






       lowerCamelCase_		     =    TFFlaubertWithLMHeadModel(A_  )

       lowerCamelCase_		     =    {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
       lowerCamelCase_		     =    model(A_  )

       self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.seq_length, self.vocab_size)  )

 def 				a__ (				self					:  str						,							A_					:  Tuple						,							A_					:  Any						,							A_					:  Any						,							A_					:  List[Any]						,							A_					:  Dict						,							A_					:  List[Any]						,							A_					:  Union[str, Any]						,							A_					:  Optional[int]						,							A_					:  List[Any]						,							)   ->	Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_		     =    TFFlaubertForQuestionAnsweringSimple(A_  )

       lowerCamelCase_		     =    {'input_ids': input_ids, 'lengths': input_lengths}

       lowerCamelCase_		     =    model(A_  )

       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					:  Optional[int]						,							A_					:  List[Any]						,							A_					:  str						,							A_					:  List[str]						,							A_					:  Dict						,							A_					:  Optional[Any]						,							A_					:  Tuple						,							A_					:  str						,							A_					:  Optional[int]						,							A_					:  Tuple						,							)   ->	List[Any]:

       """simple docstring"""






       lowerCamelCase_		     =    TFFlaubertForSequenceClassification(A_  )

       lowerCamelCase_		     =    {'input_ids': input_ids, 'lengths': input_lengths}

       lowerCamelCase_		     =    model(A_  )

       self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.type_sequence_label_size)  )

 def 				a__ (				self					:  Dict						,							A_					:  Optional[Any]						,							A_					:  List[Any]						,							A_					:  int						,							A_					:  Any						,							A_					:  Union[str, Any]						,							A_					:  str						,							A_					:  Any						,							A_					:  Union[str, Any]						,							A_					:  List[str]						,							)   ->	Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_		     =    self.num_labels
       lowerCamelCase_		     =    TFFlaubertForTokenClassification(config=A_  )
       lowerCamelCase_		     =    {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
       lowerCamelCase_		     =    model(A_  )
       self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.seq_length, self.num_labels)  )

 def 				a__ (				self					:  List[Any]						,							A_					:  Optional[int]						,							A_					:  List[Any]						,							A_					:  Optional[int]						,							A_					:  Tuple						,							A_					:  Union[str, Any]						,							A_					:  int						,							A_					:  str						,							A_					:  Tuple						,							A_					:  str						,							)   ->	Optional[int]:

       """simple docstring"""






       lowerCamelCase_		     =    self.num_choices
       lowerCamelCase_		     =    TFFlaubertForMultipleChoice(config=A_  )
       lowerCamelCase_		     =    tf.tile(tf.expand_dims(A_						,							1  )						,							(1, self.num_choices, 1)  )
       lowerCamelCase_		     =    tf.tile(tf.expand_dims(A_						,							1  )						,							(1, self.num_choices, 1)  )
       lowerCamelCase_		     =    tf.tile(tf.expand_dims(A_						,							1  )						,							(1, self.num_choices, 1)  )
       lowerCamelCase_		     =    {
           'input_ids': multiple_choice_inputs_ids,
           'attention_mask': multiple_choice_input_mask,
           'token_type_ids': multiple_choice_token_type_ids,
       }
       lowerCamelCase_		     =    model(A_  )
       self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.num_choices)  )





 def 				a__ (				self					:  Union[str, Any]  )   ->	List[Any]:

       """simple docstring"""






       lowerCamelCase_		     =    self.prepare_config_and_inputs()
       (
           (
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				(
           lowerCamelCase_
       )     ,				
       )		     =    config_and_inputs
       lowerCamelCase_		     =    {
           'input_ids': input_ids,
           'token_type_ids': token_type_ids,
           'langs': token_type_ids,
           'lengths': input_lengths,
       }
       return config, inputs_dict







@require_tf
class   A(						UpperCamelCase							,      UpperCamelCase							,      unittest.TestCase   ):



 '''simple docstring'''


 UpperCamelCase						   =						(
     (
         TFFlaubertModel,
         TFFlaubertWithLMHeadModel,
         TFFlaubertForSequenceClassification,
         TFFlaubertForQuestionAnsweringSimple,
         TFFlaubertForTokenClassification,
         TFFlaubertForMultipleChoice,
     )
     if is_tf_available()
     else ()
 )
 UpperCamelCase						   =						(
     (TFFlaubertWithLMHeadModel,) if is_tf_available() else ()
 )  # TODO (PVP): Check other models whether language generation is also applicable
 UpperCamelCase						   =						(
     {
         '''feature-extraction''': TFFlaubertModel,
         '''fill-mask''': TFFlaubertWithLMHeadModel,
         '''question-answering''': TFFlaubertForQuestionAnsweringSimple,
         '''text-classification''': TFFlaubertForSequenceClassification,
         '''token-classification''': TFFlaubertForTokenClassification,
         '''zero-shot''': TFFlaubertForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 UpperCamelCase						   =						False
 UpperCamelCase						   =						False

 def 				a__ (				self					:  Union[str, Any]						,							A_					:  Any						,							A_					:  List[Any]						,							A_					:  Union[str, Any]						,							A_					:  str						,							A_					:  List[str]  )   ->	Optional[Any]:

       """simple docstring"""






       if (
           pipeline_test_casse_name == "QAPipelineTests"
           and tokenizer_name is not None
           and not tokenizer_name.endswith('Fast'  )
       ):
             # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
             # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
             # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
             return True

       return False

 def 				a__ (				self					:  List[str]  )   ->	Optional[int]:

       """simple docstring"""






       lowerCamelCase_		     =    TFFlaubertModelTester(self  )
       lowerCamelCase_		     =    ConfigTester(self						,							config_class=A_						,							emb_dim=37  )

 def 				a__ (				self					:  List[str]  )   ->	str:

       """simple docstring"""






       self.config_tester.run_common_tests()

 def 				a__ (				self					:  int  )   ->	Optional[int]:

       """simple docstring"""






       lowerCamelCase_		     =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_flaubert_model(*A_  )

 def 				a__ (				self					:  List[str]  )   ->	Any:

       """simple docstring"""






       lowerCamelCase_		     =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_flaubert_lm_head(*A_  )

 def 				a__ (				self					:  Dict  )   ->	Tuple:

       """simple docstring"""






       lowerCamelCase_		     =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_flaubert_qa(*A_  )

 def 				a__ (				self					:  Union[str, Any]  )   ->	Tuple:

       """simple docstring"""






       lowerCamelCase_		     =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_flaubert_sequence_classif(*A_  )

 def 				a__ (				self					:  List[Any]  )   ->	Dict:

       """simple docstring"""






       lowerCamelCase_		     =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_flaubert_for_token_classification(*A_  )

 def 				a__ (				self					:  int  )   ->	Optional[int]:

       """simple docstring"""






       lowerCamelCase_		     =    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_flaubert_for_multiple_choice(*A_  )





 @slow
 def 				a__ (				self					:  Union[str, Any]  )   ->	Optional[int]:

       """simple docstring"""






       for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_		     =    TFFlaubertModel.from_pretrained(A_  )
             self.assertIsNotNone(A_  )







@require_tf
@require_sentencepiece
@require_tokenizers
class   A(						unittest.TestCase   ):



 '''simple docstring'''


 @slow
 def 				a__ (				self					:  Dict  )   ->	str:

       """simple docstring"""






       lowerCamelCase_		     =    TFFlaubertModel.from_pretrained('jplu/tf-flaubert-small-cased'  )

       lowerCamelCase_		     =    tf.convert_to_tensor(
           [[0, 158, 735, 2592, 1424, 6727, 82, 1]]						,							dtype=tf.intaa						,							)  # "J'aime flaubert !"

       lowerCamelCase_		     =    model(A_  )[0]
       lowerCamelCase_		     =    tf.TensorShape((1, 8, 512)  )
       self.assertEqual(output.shape						,							A_  )
       # compare the actual values for a slice.
       lowerCamelCase_		     =    tf.convert_to_tensor(
           [
               [
                   [-1.8768773, -1.566555, 0.27072418],
                   [-1.6920038, -0.5873505, 1.9329599],
                   [-2.9563985, -1.6993835, 1.7972052],
               ]
           ]						,							dtype=tf.floataa						,							)

       self.assertTrue(np.allclose(output[:, :3, :3].numpy()						,							expected_slice.numpy()						,							atol=1E-4  )  )



