"""simple docstring"""


import math
import unittest

from transformers import BioGptConfig, 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 (
        BioGptForCausalLM,
        BioGptForSequenceClassification,
        BioGptForTokenClassification,
        BioGptModel,
        BioGptTokenizer,
    )
    from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST


class 				a :


    def __init__(    self		:     Optional[int]      , __lowerCAmelCase		:     List[str]      , __lowerCAmelCase		:     Optional[int]=13      , __lowerCAmelCase		:     Optional[Any]=7      , __lowerCAmelCase		:     int=True      , __lowerCAmelCase		:     Optional[Any]=True      , __lowerCAmelCase		:     Union[str, Any]=False      , __lowerCAmelCase		:     List[str]=True      , __lowerCAmelCase		:     Any=99      , __lowerCAmelCase		:     Dict=32      , __lowerCAmelCase		:     int=5      , __lowerCAmelCase		:     Tuple=4      , __lowerCAmelCase		:     Tuple=37      , __lowerCAmelCase		:     Tuple="gelu"      , __lowerCAmelCase		:     Optional[Any]=0.1      , __lowerCAmelCase		:     Optional[int]=0.1      , __lowerCAmelCase		:     Optional[Any]=512      , __lowerCAmelCase		:     Any=16      , __lowerCAmelCase		:     Tuple=2      , __lowerCAmelCase		:     Any=0.02      , __lowerCAmelCase		:     Dict=3      , __lowerCAmelCase		:     Tuple=4      , __lowerCAmelCase		:     List[Any]=None      , ):
      _UpperCAmelCase         =					parent
      _UpperCAmelCase         =					batch_size
      _UpperCAmelCase         =					seq_length
      _UpperCAmelCase         =					is_training
      _UpperCAmelCase         =					use_input_mask
      _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


    def    lowerCAmelCase_     (    self		:     Any    ):
      _UpperCAmelCase         =					ids_tensor([self.batch_size, self.seq_length]      , self.vocab_size    )

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

      _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         =					self.get_config()

      return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


    def    lowerCAmelCase_     (    self		:     List[Any]    ):
      return BioGptConfig(
          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      , type_vocab_size=self.type_vocab_size      , is_decoder=__lowerCAmelCase      , initializer_range=self.initializer_range      , )


    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     Any      , __lowerCAmelCase		:     Any      , __lowerCAmelCase		:     List[str]      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     Any      , __lowerCAmelCase		:     Optional[int]      , __lowerCAmelCase		:     str    ):
      _UpperCAmelCase         =					BioGptModel(config=__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      model.eval()
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase    )
      _UpperCAmelCase         =					model(__lowerCAmelCase    )
      self.parent.assertEqual(result.last_hidden_state.shape      , (self.batch_size, self.seq_length, self.hidden_size)    )


    def    lowerCAmelCase_     (    self		:     List[str]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     Optional[int]      , __lowerCAmelCase		:     List[str]      , __lowerCAmelCase		:     Optional[Any]      , __lowerCAmelCase		:     Union[str, Any]      , __lowerCAmelCase		:     Union[str, Any]      , __lowerCAmelCase		:     Optional[Any]      , __lowerCAmelCase		:     str      , ):
      _UpperCAmelCase         =					BioGptForCausalLM(config=__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      model.eval()
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase      , token_type_ids=__lowerCAmelCase      , labels=__lowerCAmelCase    )
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.seq_length, self.vocab_size)    )


    def    lowerCAmelCase_     (    self		:     str      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     Dict      , __lowerCAmelCase		:     Optional[int]      , __lowerCAmelCase		:     Union[str, Any]      , *__lowerCAmelCase		:     str    ):
      _UpperCAmelCase         =					BioGptModel(config=__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      model.eval()

      # create attention mask
      _UpperCAmelCase         =					torch.ones(input_ids.shape      , dtype=torch.long      , device=__lowerCAmelCase    )
      _UpperCAmelCase         =					self.seq_length // 2
      _UpperCAmelCase         =					0

      # first forward pass
      _UpperCAmelCase       , _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase    ).to_tuple()

      # create hypothetical next token and extent to next_input_ids
      _UpperCAmelCase         =					ids_tensor((self.batch_size, 1)      , config.vocab_size    )

      # change a random masked slice from input_ids
      _UpperCAmelCase         =					ids_tensor((1,)      , __lowerCAmelCase    ).item() + 1
      _UpperCAmelCase         =					ids_tensor((self.batch_size, 1)      , config.vocab_size    ).squeeze(-1    )
      _UpperCAmelCase         =					random_other_next_tokens

      # append to next input_ids and attn_mask
      _UpperCAmelCase         =					torch.cat([input_ids, next_tokens]      , dim=-1    )
      _UpperCAmelCase         =					torch.cat(
          [attn_mask, torch.ones((attn_mask.shape[0], 1)      , dtype=torch.long      , device=__lowerCAmelCase    )]      , dim=1      , )

      # get two different outputs
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase    )["""last_hidden_state"""]
      _UpperCAmelCase         =					model(__lowerCAmelCase      , past_key_values=__lowerCAmelCase      , attention_mask=__lowerCAmelCase    )["""last_hidden_state"""]

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

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


    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     Dict      , __lowerCAmelCase		:     Any      , __lowerCAmelCase		:     Union[str, Any]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     Union[str, Any]      , *__lowerCAmelCase		:     str    ):
      _UpperCAmelCase         =					BioGptModel(config=__lowerCAmelCase    ).to(__lowerCAmelCase    ).eval()

      _UpperCAmelCase         =					torch.ones(input_ids.shape      , dtype=torch.long      , device=__lowerCAmelCase    )

      # first forward pass
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase      , use_cache=__lowerCAmelCase    )

      _UpperCAmelCase       , _UpperCAmelCase         =					outputs.to_tuple()

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

      # append to next input_ids and
      _UpperCAmelCase         =					torch.cat([input_ids, next_tokens]      , dim=-1    )
      _UpperCAmelCase         =					torch.cat([attention_mask, next_attn_mask]      , dim=-1    )

      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase    )["""last_hidden_state"""]
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase      , past_key_values=__lowerCAmelCase    )[
          """last_hidden_state"""
      ]

      # select random slice
      _UpperCAmelCase         =					ids_tensor((1,)      , output_from_past.shape[-1]    ).item()
      _UpperCAmelCase         =					output_from_no_past[:, -3:, random_slice_idx].detach()
      _UpperCAmelCase         =					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(__lowerCAmelCase      , __lowerCAmelCase      , atol=1e-3    )    )


    def    lowerCAmelCase_     (    self		:     Optional[Any]      , __lowerCAmelCase		:     Optional[Any]      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     Dict      , *__lowerCAmelCase		:     Optional[int]      , __lowerCAmelCase		:     List[Any]=False    ):
      _UpperCAmelCase         =					BioGptForCausalLM(__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      if gradient_checkpointing:
        model.gradient_checkpointing_enable()

      _UpperCAmelCase         =					model(__lowerCAmelCase      , labels=__lowerCAmelCase    )
      self.parent.assertEqual(result.loss.shape      , ()    )
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.seq_length, self.vocab_size)    )
      result.loss.backward()


    def    lowerCAmelCase_     (    self		:     Union[str, Any]      , __lowerCAmelCase		:     Union[str, Any]      , *__lowerCAmelCase		:     Union[str, Any]    ):
      _UpperCAmelCase         =					BioGptModel(__lowerCAmelCase    )
      _UpperCAmelCase         =					model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers    )
      for key in model.state_dict().keys():
        if "c_proj" in key and "weight" in key:
          self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]    ) - model_std    )      , 0.001    )
          self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]    ) - 0.0    )      , 0.01    )


    def    lowerCAmelCase_     (    self		:     Any      , __lowerCAmelCase		:     Dict      , __lowerCAmelCase		:     Optional[int]      , __lowerCAmelCase		:     List[str]      , __lowerCAmelCase		:     List[str]      , __lowerCAmelCase		:     Tuple      , *__lowerCAmelCase		:     Tuple    ):
      _UpperCAmelCase         =					self.num_labels
      _UpperCAmelCase         =					BioGptForTokenClassification(__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      model.eval()
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase      , token_type_ids=__lowerCAmelCase    )
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.seq_length, self.num_labels)    )


    def    lowerCAmelCase_     (    self		:     List[str]    ):
      _UpperCAmelCase         =					self.prepare_config_and_inputs()
      (
          (
          _UpperCAmelCase
      )       , (
          _UpperCAmelCase
      )       , (
          _UpperCAmelCase
      )       , (
          _UpperCAmelCase
      )       , (
          _UpperCAmelCase
      )       , (
          _UpperCAmelCase
      )       , (
          _UpperCAmelCase
      )       , 
      )         =					config_and_inputs
      _UpperCAmelCase         =					{"""input_ids""": input_ids, """attention_mask""": input_mask}
      return config, inputs_dict



@require_torch
class 				a (						lowerCAmelCase_		,							lowerCAmelCase_		,							lowerCAmelCase_		,							unittest.TestCase      ):
    _snake_case   :     List[Any]   							=							(
        (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
        if is_torch_available()
        else ()
    )
    _snake_case   :     Tuple   							=							(BioGptForCausalLM,) if is_torch_available() else ()
    _snake_case   :     Optional[Any]   							=							(
        {
            'feature-extraction': BioGptModel,
            'text-classification': BioGptForSequenceClassification,
            'text-generation': BioGptForCausalLM,
            'token-classification': BioGptForTokenClassification,
            'zero-shot': BioGptForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    _snake_case   :     int   							=							False


    def    lowerCAmelCase_     (    self		:     int    ):
      _UpperCAmelCase         =					BioGptModelTester(self    )
      _UpperCAmelCase         =					ConfigTester(self      , config_class=__lowerCAmelCase      , hidden_size=37    )


    def    lowerCAmelCase_     (    self		:     Union[str, Any]    ):
      self.config_tester.run_common_tests()


    def    lowerCAmelCase_     (    self		:     Optional[int]    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     str    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
        _UpperCAmelCase         =					type
        self.model_tester.create_and_check_model(*__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     Dict    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     Optional[int]    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_forward_and_backwards(*__lowerCAmelCase      , gradient_checkpointing=__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     Optional[Any]    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     List[str]    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_biogpt_weight_initialization(*__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     Dict    ):
      _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_biogpt_for_token_classification(*__lowerCAmelCase    )


    @slow
    def    lowerCAmelCase_     (    self		:     int    ):
      _UpperCAmelCase         =					BioGptForCausalLM.from_pretrained("""microsoft/biogpt"""    )
      model.to(__lowerCAmelCase    )
      _UpperCAmelCase         =					BioGptTokenizer.from_pretrained("""microsoft/biogpt"""    )

      _UpperCAmelCase         =					"""left"""

      # Define PAD Token = EOS Token = 50256
      _UpperCAmelCase         =					tokenizer.eos_token
      _UpperCAmelCase         =					model.config.eos_token_id

      # use different length sentences to test batching
      _UpperCAmelCase         =					[
          """Hello, my dog is a little""",
          """Today, I""",
      ]

      _UpperCAmelCase         =					tokenizer(__lowerCAmelCase      , return_tensors="""pt"""      , padding=__lowerCAmelCase    )
      _UpperCAmelCase         =					inputs["""input_ids"""].to(__lowerCAmelCase    )

      _UpperCAmelCase         =					model.generate(
          input_ids=__lowerCAmelCase      , attention_mask=inputs["""attention_mask"""].to(__lowerCAmelCase    )      , )

      _UpperCAmelCase         =					tokenizer(sentences[0]      , return_tensors="""pt"""    ).input_ids.to(__lowerCAmelCase    )
      _UpperCAmelCase         =					model.generate(input_ids=__lowerCAmelCase    )

      _UpperCAmelCase         =					inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item()
      _UpperCAmelCase         =					tokenizer(sentences[1]      , return_tensors="""pt"""    ).input_ids.to(__lowerCAmelCase    )
      _UpperCAmelCase         =					model.generate(input_ids=__lowerCAmelCase      , max_length=model.config.max_length - num_paddings    )

      _UpperCAmelCase         =					tokenizer.batch_decode(__lowerCAmelCase      , skip_special_tokens=__lowerCAmelCase    )
      _UpperCAmelCase         =					tokenizer.decode(output_non_padded[0]      , skip_special_tokens=__lowerCAmelCase    )
      _UpperCAmelCase         =					tokenizer.decode(output_padded[0]      , skip_special_tokens=__lowerCAmelCase    )

      _UpperCAmelCase         =					[
          """Hello, my dog is a little bit bigger than a little bit.""",
          """Today, I have a good idea of how to use the information""",
      ]
      self.assertListEqual(__lowerCAmelCase      , __lowerCAmelCase    )
      self.assertListEqual(__lowerCAmelCase      , [non_padded_sentence, padded_sentence]    )


    @slow
    def    lowerCAmelCase_     (    self		:     Optional[int]    ):
      for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _UpperCAmelCase         =					BioGptModel.from_pretrained(__lowerCAmelCase    )
        self.assertIsNotNone(__lowerCAmelCase    )


    def    lowerCAmelCase_     (    self		:     Tuple    ):
      _UpperCAmelCase       , _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs_for_common()
      _UpperCAmelCase         =					3
      _UpperCAmelCase         =					input_dict["""input_ids"""]
      _UpperCAmelCase         =					input_ids.ne(1    ).to(__lowerCAmelCase    )
      _UpperCAmelCase         =					ids_tensor([self.model_tester.batch_size]      , self.model_tester.type_sequence_label_size    )
      _UpperCAmelCase         =					BioGptForSequenceClassification(__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      model.eval()
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase      , labels=__lowerCAmelCase    )
      self.assertEqual(result.logits.shape      , (self.model_tester.batch_size, self.model_tester.num_labels)    )


    def    lowerCAmelCase_     (    self		:     int    ):
      _UpperCAmelCase       , _UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs_for_common()
      _UpperCAmelCase         =					3
      _UpperCAmelCase         =					"""multi_label_classification"""
      _UpperCAmelCase         =					input_dict["""input_ids"""]
      _UpperCAmelCase         =					input_ids.ne(1    ).to(__lowerCAmelCase    )
      _UpperCAmelCase         =					ids_tensor(
          [self.model_tester.batch_size, config.num_labels]      , self.model_tester.type_sequence_label_size    ).to(torch.float    )
      _UpperCAmelCase         =					BioGptForSequenceClassification(__lowerCAmelCase    )
      model.to(__lowerCAmelCase    )
      model.eval()
      _UpperCAmelCase         =					model(__lowerCAmelCase      , attention_mask=__lowerCAmelCase      , labels=__lowerCAmelCase    )
      self.assertEqual(result.logits.shape      , (self.model_tester.batch_size, self.model_tester.num_labels)    )



@require_torch
class 				a (						unittest.TestCase      ):


    @slow
    def    lowerCAmelCase_     (    self		:     Dict    ):
      _UpperCAmelCase         =					BioGptForCausalLM.from_pretrained("""microsoft/biogpt"""    )
      _UpperCAmelCase         =					torch.tensor([[2, 4805, 9, 656, 21]]    )
      _UpperCAmelCase         =					model(__lowerCAmelCase    )[0]

      _UpperCAmelCase         =					4_2384

      _UpperCAmelCase         =					torch.Size((1, 5, vocab_size)    )
      self.assertEqual(output.shape      , __lowerCAmelCase    )

      _UpperCAmelCase         =					torch.tensor(
          [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]]    )

      self.assertTrue(torch.allclose(output[:, :3, :3]      , __lowerCAmelCase      , atol=1e-4    )    )


    @slow
    def    lowerCAmelCase_     (    self		:     str    ):
      _UpperCAmelCase         =					BioGptTokenizer.from_pretrained("""microsoft/biogpt"""    )
      _UpperCAmelCase         =					BioGptForCausalLM.from_pretrained("""microsoft/biogpt"""    )
      model.to(__lowerCAmelCase    )

      torch.manual_seed(0    )
      _UpperCAmelCase         =					tokenizer("""COVID-19 is"""      , return_tensors="""pt"""    ).to(__lowerCAmelCase    )
      _UpperCAmelCase         =					model.generate(
          **__lowerCAmelCase      , min_length=100      , max_length=1024      , num_beams=5      , early_stopping=__lowerCAmelCase      , )
      _UpperCAmelCase         =					tokenizer.decode(output_ids[0]      , skip_special_tokens=__lowerCAmelCase    )

      _UpperCAmelCase         =					(
          """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the"""
          """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and"""
          """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),"""
          """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and"""
          """ more than 800,000 deaths."""
      )
      self.assertEqual(__lowerCAmelCase      , __lowerCAmelCase    )

"""simple docstring"""


from sklearn.metrics import recall_score

import datasets


UpperCAmelCase__     						=  """
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


UpperCAmelCase__     						=  """
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while 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 y_true and y_pred are used in sorted order. Defaults to None.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **average** (`string`): This parameter is required for multiclass/multilabel targets. If 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 target labels and predictions 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. Note that it 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`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


UpperCAmelCase__     						=  """
@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    lowerCAmelCase_     (    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.recall_score.html"""]      , )


    def    lowerCAmelCase_     (    self		:     List[Any]      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     Optional[Any]      , __lowerCAmelCase		:     int=None      , __lowerCAmelCase		:     Dict=1      , __lowerCAmelCase		:     List[str]="binary"      , __lowerCAmelCase		:     Any=None      , __lowerCAmelCase		:     int="warn"      , ):
      _UpperCAmelCase         =					recall_score(
          __lowerCAmelCase      , __lowerCAmelCase      , labels=__lowerCAmelCase      , pos_label=__lowerCAmelCase      , average=__lowerCAmelCase      , sample_weight=__lowerCAmelCase      , zero_division=__lowerCAmelCase      , )
      return {"recall": float(__lowerCAmelCase    ) if score.size == 1 else score}
