






import unittest

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


if is_torch_available():
 import torch

 from transformers import BertGenerationDecoder, BertGenerationEncoder



class 				_UpperCamelCase      :


      def __init__(						self       ,    __UpperCamelCase       ,    __UpperCamelCase=1_3       ,    __UpperCamelCase=7       ,    __UpperCamelCase=True       ,    __UpperCamelCase=True       ,    __UpperCamelCase=9_9       ,    __UpperCamelCase=3_2       ,    __UpperCamelCase=5       ,    __UpperCamelCase=4       ,    __UpperCamelCase=3_7       ,    __UpperCamelCase="gelu"       ,    __UpperCamelCase=0.1       ,    __UpperCamelCase=0.1       ,    __UpperCamelCase=5_0       ,    __UpperCamelCase=0.0_2       ,    __UpperCamelCase=True       ,    __UpperCamelCase=None       ,    )->						List[str]:
           __lowerCAmelCase             =       parent
           __lowerCAmelCase             =       batch_size
           __lowerCAmelCase             =       seq_length
           __lowerCAmelCase             =       is_training
           __lowerCAmelCase             =       use_input_mask
           __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             =       initializer_range
           __lowerCAmelCase             =       use_labels
           __lowerCAmelCase             =       scope


      def 			__UpperCAmelCase		(						self						)->						Optional[int]:
           __lowerCAmelCase             =       ids_tensor([self.batch_size, self.seq_length]       ,    self.vocab_size						)

           __lowerCAmelCase             =       None
           if self.use_input_mask:
                __lowerCAmelCase             =       random_attention_mask([self.batch_size, self.seq_length]						)

           if self.use_labels:
                __lowerCAmelCase             =       ids_tensor([self.batch_size, self.seq_length]       ,    self.vocab_size						)

           __lowerCAmelCase             =       self.get_config()

           return config, input_ids, input_mask, token_labels


      def 			__UpperCAmelCase		(						self						)->						Union[str, Any]:
           return BertGenerationConfig(
               vocab_size=self.vocab_size       ,    hidden_size=self.hidden_size       ,    num_hidden_layers=self.num_hidden_layers       ,    num_attention_heads=self.num_attention_heads       ,    intermediate_size=self.intermediate_size       ,    hidden_act=self.hidden_act       ,    hidden_dropout_prob=self.hidden_dropout_prob       ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,    max_position_embeddings=self.max_position_embeddings       ,    is_decoder=__UpperCamelCase       ,    initializer_range=self.initializer_range       ,    )


      def 			__UpperCAmelCase		(						self						)->						Dict:
           (
               (
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			
           )             =       self.prepare_config_and_inputs()

           __lowerCAmelCase             =       True
           __lowerCAmelCase             =       floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
           __lowerCAmelCase             =       ids_tensor([self.batch_size, self.seq_length]       ,    vocab_size=2						)

           return (
               config,
               input_ids,
               input_mask,
               token_labels,
               encoder_hidden_states,
               encoder_attention_mask,
           )


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    **__UpperCamelCase       ,    )->						Tuple:
           __lowerCAmelCase             =       BertGenerationEncoder(config=__UpperCamelCase						)
           model.to(__UpperCamelCase						)
           model.eval()
           __lowerCAmelCase             =       model(__UpperCamelCase       ,    attention_mask=__UpperCamelCase						)
           __lowerCAmelCase             =       model(__UpperCamelCase						)
           self.parent.assertEqual(result.last_hidden_state.shape       ,    (self.batch_size, self.seq_length, self.hidden_size)						)


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    **__UpperCamelCase       ,    )->						List[str]:
           __lowerCAmelCase             =       True
           __lowerCAmelCase             =       BertGenerationEncoder(config=__UpperCamelCase						)
           model.to(__UpperCamelCase						)
           model.eval()
           __lowerCAmelCase             =       model(
               __UpperCamelCase       ,    attention_mask=__UpperCamelCase       ,    encoder_hidden_states=__UpperCamelCase       ,    encoder_attention_mask=__UpperCamelCase       ,    )
           __lowerCAmelCase             =       model(
               __UpperCamelCase       ,    attention_mask=__UpperCamelCase       ,    encoder_hidden_states=__UpperCamelCase       ,    )
           self.parent.assertEqual(result.last_hidden_state.shape       ,    (self.batch_size, self.seq_length, self.hidden_size)						)


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    **__UpperCamelCase       ,    )->						Tuple:
           __lowerCAmelCase             =       True
           __lowerCAmelCase             =       True
           __lowerCAmelCase             =       BertGenerationDecoder(config=__UpperCamelCase						).to(__UpperCamelCase						).eval()

           # first forward pass
           __lowerCAmelCase             =       model(
               __UpperCamelCase       ,    attention_mask=__UpperCamelCase       ,    encoder_hidden_states=__UpperCamelCase       ,    encoder_attention_mask=__UpperCamelCase       ,    use_cache=__UpperCamelCase       ,    )
           __lowerCAmelCase             =       outputs.past_key_values

           # create hypothetical multiple next token and extent to next_input_ids
           __lowerCAmelCase             =       ids_tensor((self.batch_size, 3)       ,    config.vocab_size						)
           __lowerCAmelCase             =       ids_tensor((self.batch_size, 3)       ,    vocab_size=2						)

           # append to next input_ids and
           __lowerCAmelCase             =       torch.cat([input_ids, next_tokens]       ,    dim=-1						)
           __lowerCAmelCase             =       torch.cat([input_mask, next_mask]       ,    dim=-1						)

           __lowerCAmelCase             =       model(
               __UpperCamelCase       ,    attention_mask=__UpperCamelCase       ,    encoder_hidden_states=__UpperCamelCase       ,    encoder_attention_mask=__UpperCamelCase       ,    output_hidden_states=__UpperCamelCase       ,    )["hidden_states"][0]
           __lowerCAmelCase             =       model(
               __UpperCamelCase       ,    attention_mask=__UpperCamelCase       ,    encoder_hidden_states=__UpperCamelCase       ,    encoder_attention_mask=__UpperCamelCase       ,    past_key_values=__UpperCamelCase       ,    output_hidden_states=__UpperCamelCase       ,    )["hidden_states"][0]

           # select random slice
           __lowerCAmelCase             =       ids_tensor((1,)       ,    output_from_past.shape[-1]						).item()
           __lowerCAmelCase             =       output_from_no_past[:, -3:, random_slice_idx].detach()
           __lowerCAmelCase             =       output_from_past[:, :, random_slice_idx].detach()

           self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]						)

           # test that outputs are equal for slice
           self.parent.assertTrue(torch.allclose(__UpperCamelCase       ,    __UpperCamelCase       ,    atol=1e-3						)						)


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    *__UpperCamelCase       ,    )->						Any:
           __lowerCAmelCase             =       BertGenerationDecoder(__UpperCamelCase						)
           model.to(__UpperCamelCase						)
           model.eval()
           __lowerCAmelCase             =       model(__UpperCamelCase       ,    attention_mask=__UpperCamelCase       ,    labels=__UpperCamelCase						)
           self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.seq_length, self.vocab_size)						)


      def 			__UpperCAmelCase		(						self						)->						Optional[int]:
           __lowerCAmelCase      ,			__lowerCAmelCase      ,			__lowerCAmelCase      ,			__lowerCAmelCase             =       self.prepare_config_and_inputs()
           __lowerCAmelCase             =       {"input_ids": input_ids, "attention_mask": input_mask}
           return config, inputs_dict



@require_torch
class 				_UpperCamelCase      (a_				,		a_				,		a_				,		unittest.TestCase      ):
      snake_case_	=				(BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
      snake_case_	=				(BertGenerationDecoder,) if is_torch_available() else ()
      snake_case_	=				(
          {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder}
          if is_torch_available()
          else {}
      )


      def 			__UpperCAmelCase		(						self						)->						Tuple:
           __lowerCAmelCase             =       BertGenerationEncoderTester(self						)
           __lowerCAmelCase             =       ConfigTester(self       ,    config_class=__UpperCamelCase       ,    hidden_size=3_7						)


      def 			__UpperCAmelCase		(						self						)->						Tuple:
           self.config_tester.run_common_tests()


      def 			__UpperCAmelCase		(						self						)->						List[str]:
           __lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__UpperCamelCase						)


      def 			__UpperCAmelCase		(						self						)->						Tuple:
           __lowerCAmelCase      ,			__lowerCAmelCase      ,			__lowerCAmelCase      ,			__lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs()
           __lowerCAmelCase             =       "bert"
           self.model_tester.create_and_check_model(__UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase						)


      def 			__UpperCAmelCase		(						self						)->						Union[str, Any]:
           __lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_model_as_decoder(*__UpperCamelCase						)


      def 			__UpperCAmelCase		(						self						)->						List[Any]:
           __lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(*__UpperCamelCase						)


      def 			__UpperCAmelCase		(						self						)->						Dict:
           # This regression test was failing with PyTorch < 1.3
           (
               (
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			(
               __lowerCAmelCase
           )      ,			
           )             =       self.model_tester.prepare_config_and_inputs_for_decoder()

           __lowerCAmelCase             =       None

           self.model_tester.create_and_check_model_as_decoder(
               __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    )


      def 			__UpperCAmelCase		(						self						)->						Tuple:
           __lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_for_causal_lm(*__UpperCamelCase						)


      @slow
      def 			__UpperCAmelCase		(						self						)->						Union[str, Any]:
           __lowerCAmelCase             =       BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder"						)
           self.assertIsNotNone(__UpperCamelCase						)



@require_torch
class 				_UpperCamelCase      (unittest.TestCase      ):


      @slow
      def 			__UpperCAmelCase		(						self						)->						Optional[Any]:
           __lowerCAmelCase             =       BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder"						)
           __lowerCAmelCase             =       torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]						)
           with torch.no_grad():
                __lowerCAmelCase             =       model(__UpperCamelCase						)[0]
           __lowerCAmelCase             =       torch.Size([1, 8, 1_0_2_4]						)
           self.assertEqual(output.shape       ,    __UpperCamelCase						)
           __lowerCAmelCase             =       torch.tensor(
               [[[0.1_7_7_5, 0.0_0_8_3, -0.0_3_2_1], [1.6_0_0_2, 0.1_2_8_7, 0.3_9_1_2], [2.1_4_7_3, 0.5_7_9_1, 0.6_0_6_6]]]						)
           self.assertTrue(torch.allclose(output[:, :3, :3]       ,    __UpperCamelCase       ,    atol=1e-4						)						)



@require_torch
class 				_UpperCamelCase      (unittest.TestCase      ):


      @slow
      def 			__UpperCAmelCase		(						self						)->						Optional[Any]:
           __lowerCAmelCase             =       BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder"						)
           __lowerCAmelCase             =       torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]						)
           with torch.no_grad():
                __lowerCAmelCase             =       model(__UpperCamelCase						)[0]
           __lowerCAmelCase             =       torch.Size([1, 8, 5_0_3_5_8]						)
           self.assertEqual(output.shape       ,    __UpperCamelCase						)
           __lowerCAmelCase             =       torch.tensor(
               [[[-0.5_7_8_8, -2.5_9_9_4, -3.7_0_5_4], [0.0_4_3_8, 4.7_9_9_7, 1.8_7_9_5], [1.5_8_6_2, 6.6_4_0_9, 4.4_6_3_8]]]						)
           self.assertTrue(torch.allclose(output[:, :3, :3]       ,    __UpperCamelCase       ,    atol=1e-4						)						)














from sklearn.metrics import fa_score

import datasets


lowerCamelCase      :       Union[str, 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)
'''


lowerCamelCase      :       Optional[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. ])}
'''


lowerCamelCase      :       Optional[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 				_UpperCamelCase      (datasets.Metric      ):


      def 			__UpperCAmelCase		(						self						)->						Tuple:
           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 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase=None       ,    __UpperCamelCase=1       ,    __UpperCamelCase="binary"       ,    __UpperCamelCase=None						)->						Optional[int]:
           __lowerCAmelCase             =       fa_score(
               __UpperCamelCase       ,    __UpperCamelCase       ,    labels=__UpperCamelCase       ,    pos_label=__UpperCamelCase       ,    average=__UpperCamelCase       ,    sample_weight=__UpperCamelCase						)
           return {"f1": float(__UpperCamelCase						) if score.size == 1 else score}






