

import unittest

from transformers import ElectraConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 (
      MODEL_FOR_PRETRAINING_MAPPING,
      ElectraForCausalLM,
      ElectraForMaskedLM,
      ElectraForMultipleChoice,
      ElectraForPreTraining,
      ElectraForQuestionAnswering,
      ElectraForSequenceClassification,
      ElectraForTokenClassification,
      ElectraModel,
  )
  from transformers.models.electra.modeling_electra import ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST






class 							A_				:


     def __init__(							self    :	Optional[int]    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	Optional[int]=1_3    ,						UpperCAmelCase    :	Dict=7    ,						UpperCAmelCase    :	Any=True    ,						UpperCAmelCase    :	str=True    ,						UpperCAmelCase    :	Union[str, Any]=True    ,						UpperCAmelCase    :	List[Any]=True    ,						UpperCAmelCase    :	Union[str, Any]=9_9    ,						UpperCAmelCase    :	Optional[int]=3_2    ,						UpperCAmelCase    :	List[str]=5    ,						UpperCAmelCase    :	Any=4    ,						UpperCAmelCase    :	int=3_7    ,						UpperCAmelCase    :	int="gelu"    ,						UpperCAmelCase    :	Union[str, Any]=0.1    ,						UpperCAmelCase    :	Dict=0.1    ,						UpperCAmelCase    :	str=5_1_2    ,						UpperCAmelCase    :	Tuple=1_6    ,						UpperCAmelCase    :	Optional[int]=2    ,						UpperCAmelCase    :	int=0.02    ,						UpperCAmelCase    :	List[str]=3    ,						UpperCAmelCase    :	Any=4    ,						UpperCAmelCase    :	List[Any]=None    ,						)							->			Union[str, Any]:
      __lowerCAmelCase:     List[Any]     			=   parent
      __lowerCAmelCase:     List[Any]     			=   batch_size
      __lowerCAmelCase:     Optional[int]     			=   seq_length
      __lowerCAmelCase:     Union[str, Any]     			=   is_training
      __lowerCAmelCase:     Tuple     			=   use_input_mask
      __lowerCAmelCase:     Any     			=   use_token_type_ids
      __lowerCAmelCase:     List[str]     			=   use_labels
      __lowerCAmelCase:     List[Any]     			=   vocab_size
      __lowerCAmelCase:     Dict     			=   hidden_size
      __lowerCAmelCase:     Optional[Any]     			=   num_hidden_layers
      __lowerCAmelCase:     Dict     			=   num_attention_heads
      __lowerCAmelCase:     int     			=   intermediate_size
      __lowerCAmelCase:     Any     			=   hidden_act
      __lowerCAmelCase:     Optional[Any]     			=   hidden_dropout_prob
      __lowerCAmelCase:     Any     			=   attention_probs_dropout_prob
      __lowerCAmelCase:     Any     			=   max_position_embeddings
      __lowerCAmelCase:     str     			=   type_vocab_size
      __lowerCAmelCase:     Union[str, Any]     			=   type_sequence_label_size
      __lowerCAmelCase:     Tuple     			=   initializer_range
      __lowerCAmelCase:     Any     			=   num_labels
      __lowerCAmelCase:     Optional[int]     			=   num_choices
      __lowerCAmelCase:     Dict     			=   scope


     def 						UpperCAmelCase						(							self    :	List[Any]      )							->			Optional[Any]:
      __lowerCAmelCase:     List[str]     			=   ids_tensor([self.batch_size, self.seq_length]    ,						self.vocab_size      )

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

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

      __lowerCAmelCase:     Optional[Any]     			=   None
      __lowerCAmelCase:     Optional[int]     			=   None
      __lowerCAmelCase:     str     			=   None
      if self.use_labels:
       __lowerCAmelCase:     Tuple     			=   ids_tensor([self.batch_size]    ,						self.type_sequence_label_size      )
       __lowerCAmelCase:     str     			=   ids_tensor([self.batch_size, self.seq_length]    ,						self.num_labels      )
       __lowerCAmelCase:     Union[str, Any]     			=   ids_tensor([self.batch_size]    ,						self.num_choices      )
       __lowerCAmelCase:     Optional[int]     			=   ids_tensor([self.batch_size, self.seq_length]    ,						1      )

      __lowerCAmelCase:     Union[str, Any]     			=   self.get_config()

      return (
          config,
          input_ids,
          token_type_ids,
          input_mask,
          sequence_labels,
          token_labels,
          choice_labels,
          fake_token_labels,
      )


     def 						UpperCAmelCase						(							self    :	str      )							->			int:
      return ElectraConfig(
          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=UpperCAmelCase    ,						initializer_range=self.initializer_range    ,						)


     def 						UpperCAmelCase						(							self    :	List[str]      )							->			List[str]:
      (
          (
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							
      ):     str     			=   self.prepare_config_and_inputs()

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

      return (
          config,
          input_ids,
          token_type_ids,
          input_mask,
          sequence_labels,
          token_labels,
          choice_labels,
          encoder_hidden_states,
          encoder_attention_mask,
      )


     def 						UpperCAmelCase						(							self    :	Dict    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	str    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	Any    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	int    ,						)							->			Union[str, Any]:
      __lowerCAmelCase:     Union[str, Any]     			=   ElectraModel(config=UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     int     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase      )
      __lowerCAmelCase:     Tuple     			=   model(UpperCAmelCase    ,						token_type_ids=UpperCAmelCase      )
      __lowerCAmelCase:     Union[str, Any]     			=   model(UpperCAmelCase      )
      self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)      )


     def 						UpperCAmelCase						(							self    :	int    ,						UpperCAmelCase    :	List[Any]    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	List[Any]    ,						UpperCAmelCase    :	Union[str, Any]    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	Optional[int]    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	List[Any]    ,						)							->			int:
      __lowerCAmelCase:     Optional[int]     			=   True
      __lowerCAmelCase:     Dict     			=   ElectraModel(UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     Optional[int]     			=   model(
          UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						encoder_hidden_states=UpperCAmelCase    ,						encoder_attention_mask=UpperCAmelCase    ,						)
      __lowerCAmelCase:     int     			=   model(
          UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						encoder_hidden_states=UpperCAmelCase    ,						)
      __lowerCAmelCase:     List[Any]     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase      )
      self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)      )


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


     def 						UpperCAmelCase						(							self    :	Optional[Any]    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	Optional[int]    ,						UpperCAmelCase    :	str    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	Any    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	Any    ,						)							->			str:
      __lowerCAmelCase:     Any     			=   ElectraForCausalLM(config=UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     Tuple     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						labels=UpperCAmelCase      )
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length, self.vocab_size)      )


     def 						UpperCAmelCase						(							self    :	Union[str, Any]    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	Any    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	Optional[Any]    ,						)							->			Any:
      __lowerCAmelCase:     Optional[int]     			=   self.num_labels
      __lowerCAmelCase:     List[str]     			=   ElectraForTokenClassification(config=UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     Optional[Any]     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						labels=UpperCAmelCase      )
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length, self.num_labels)      )


     def 						UpperCAmelCase						(							self    :	int    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	List[Any]    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	str    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	Union[str, Any]    ,						UpperCAmelCase    :	Optional[Any]    ,						)							->			Any:
      __lowerCAmelCase:     Union[str, Any]     			=   self.num_labels
      __lowerCAmelCase:     Optional[int]     			=   ElectraForPreTraining(config=UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     str     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						labels=UpperCAmelCase      )
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length)      )


     def 						UpperCAmelCase						(							self    :	int    ,						UpperCAmelCase    :	Any    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	str    ,						UpperCAmelCase    :	Optional[int]    ,						UpperCAmelCase    :	Union[str, Any]    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	int    ,						)							->			Optional[int]:
      __lowerCAmelCase:     List[str]     			=   self.num_labels
      __lowerCAmelCase:     Tuple     			=   ElectraForSequenceClassification(UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     Tuple     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						labels=UpperCAmelCase      )
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels)      )


     def 						UpperCAmelCase						(							self    :	int    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	List[Any]    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	Tuple    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	List[str]    ,						)							->			Optional[Any]:
      __lowerCAmelCase:     Optional[int]     			=   ElectraForQuestionAnswering(config=UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     List[str]     			=   model(
          UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						start_positions=UpperCAmelCase    ,						end_positions=UpperCAmelCase    ,						)
      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 						UpperCAmelCase						(							self    :	Optional[int]    ,						UpperCAmelCase    :	Optional[int]    ,						UpperCAmelCase    :	List[Any]    ,						UpperCAmelCase    :	Dict    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	Optional[Any]    ,						UpperCAmelCase    :	Any    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	Dict    ,						)							->			Optional[Any]:
      __lowerCAmelCase:     Optional[Any]     			=   self.num_choices
      __lowerCAmelCase:     Optional[int]     			=   ElectraForMultipleChoice(config=UpperCAmelCase      )
      model.to(UpperCAmelCase      )
      model.eval()
      __lowerCAmelCase:     Optional[int]     			=   input_ids.unsqueeze(1      ).expand(-1    ,						self.num_choices    ,						-1      ).contiguous()
      __lowerCAmelCase:     Optional[int]     			=   token_type_ids.unsqueeze(1      ).expand(-1    ,						self.num_choices    ,						-1      ).contiguous()
      __lowerCAmelCase:     Dict     			=   input_mask.unsqueeze(1      ).expand(-1    ,						self.num_choices    ,						-1      ).contiguous()
      __lowerCAmelCase:     Tuple     			=   model(
          UpperCAmelCase    ,						attention_mask=UpperCAmelCase    ,						token_type_ids=UpperCAmelCase    ,						labels=UpperCAmelCase    ,						)
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_choices)      )


     def 						UpperCAmelCase						(							self    :	List[str]      )							->			Any:
      __lowerCAmelCase:     Dict     			=   self.prepare_config_and_inputs()
      (
          (
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							(
          __lowerCAmelCase
      )			,							
      ):     Optional[Any]     			=   config_and_inputs
      __lowerCAmelCase:     List[str]     			=   {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
      return config, inputs_dict







@require_torch
class 							A_				(	snake_case__							,			snake_case__							,			unittest.TestCase      ):
     _lowercase    :  Tuple          =			(
         (
             ElectraModel,
             ElectraForPreTraining,
             ElectraForMaskedLM,
             ElectraForCausalLM,
             ElectraForMultipleChoice,
             ElectraForTokenClassification,
             ElectraForSequenceClassification,
             ElectraForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     _lowercase    :  Optional[Any]          =			(
         {
             'feature-extraction': ElectraModel,
             'fill-mask': ElectraForMaskedLM,
             'question-answering': ElectraForQuestionAnswering,
             'text-classification': ElectraForSequenceClassification,
             'text-generation': ElectraForCausalLM,
             'token-classification': ElectraForTokenClassification,
             'zero-shot': ElectraForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     _lowercase    :  Dict          =			True


     def 						UpperCAmelCase						(							self    :	str    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	int    ,						UpperCAmelCase    :	Tuple=False      )							->			List[Any]:
      __lowerCAmelCase:     List[Any]     			=   super()._prepare_for_class(UpperCAmelCase    ,						UpperCAmelCase    ,						return_labels=UpperCAmelCase      )

      if return_labels:
       if model_class in get_values(UpperCAmelCase      ):
        __lowerCAmelCase:     Tuple     			=   torch.zeros(
            (self.model_tester.batch_size, self.model_tester.seq_length)    ,						dtype=torch.long    ,						device=UpperCAmelCase      )
      return inputs_dict


     def 						UpperCAmelCase						(							self    :	List[str]      )							->			Optional[Any]:
      __lowerCAmelCase:     Tuple     			=   ElectraModelTester(self      )
      __lowerCAmelCase:     Optional[Any]     			=   ConfigTester(self    ,						config_class=UpperCAmelCase    ,						hidden_size=3_7      )


     def 						UpperCAmelCase						(							self    :	Tuple      )							->			Optional[Any]:
      self.config_tester.run_common_tests()


     def 						UpperCAmelCase						(							self    :	Union[str, Any]      )							->			List[Any]:
      __lowerCAmelCase:     Any     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_model(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Dict      )							->			Tuple:
      __lowerCAmelCase:     Optional[Any]     			=   self.model_tester.prepare_config_and_inputs_for_decoder()
      self.model_tester.create_and_check_electra_model_as_decoder(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Optional[int]      )							->			Union[str, Any]:
      __lowerCAmelCase:     Any     			=   self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
       __lowerCAmelCase:     List[Any]     			=   type
       self.model_tester.create_and_check_electra_model(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Tuple      )							->			List[str]:
      __lowerCAmelCase:     Dict     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_for_masked_lm(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Any      )							->			Tuple:
      __lowerCAmelCase:     Optional[int]     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_for_token_classification(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Tuple      )							->			Tuple:
      __lowerCAmelCase:     Any     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_for_pretraining(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Optional[int]      )							->			str:
      __lowerCAmelCase:     int     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_for_sequence_classification(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	str      )							->			Dict:
      __lowerCAmelCase:     str     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_for_question_answering(*UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	str      )							->			str:
      __lowerCAmelCase:     Optional[int]     			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_electra_for_multiple_choice(*UpperCAmelCase      )


     @slow
     def 						UpperCAmelCase						(							self    :	Union[str, Any]      )							->			int:
      for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __lowerCAmelCase:     Dict     			=   ElectraModel.from_pretrained(UpperCAmelCase      )
       self.assertIsNotNone(UpperCAmelCase      )


     def 						UpperCAmelCase						(							self    :	Union[str, Any]      )							->			Any:
      __lowerCAmelCase:     int     			=   self.model_tester.prepare_config_and_inputs_for_decoder()
      self.model_tester.create_and_check_electra_for_causal_lm(*UpperCAmelCase      )







@require_torch
class 							A_				(	unittest.TestCase      ):


     @slow
     def 						UpperCAmelCase						(							self    :	Optional[Any]      )							->			Union[str, Any]:
      __lowerCAmelCase:     Tuple     			=   ElectraModel.from_pretrained('google/electra-small-discriminator'      )
      __lowerCAmelCase:     Optional[Any]     			=   torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]      )
      __lowerCAmelCase:     Union[str, Any]     			=   torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]      )
      __lowerCAmelCase:     Optional[int]     			=   model(UpperCAmelCase    ,						attention_mask=UpperCAmelCase      )[0]
      __lowerCAmelCase:     List[Any]     			=   torch.Size((1, 1_1, 2_5_6)      )
      self.assertEqual(output.shape    ,						UpperCAmelCase      )
      __lowerCAmelCase:     Optional[int]     			=   torch.tensor(
          [[[0.4471, 0.6821, -0.3265], [0.4627, 0.5255, -0.3668], [0.4532, 0.3313, -0.4344]]]      )

      self.assertTrue(torch.allclose(output[:, 1:4, 1:4]    ,						UpperCAmelCase    ,						atol=1E-4      )      )








from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


_a	 =     '''\
@inproceedings{xu-etal-2016-optimizing,
title = {Optimizing Statistical Machine Translation for Text Simplification},
authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},
journal = {Transactions of the Association for Computational Linguistics},
volume = {4},
year={2016},
url = {https://www.aclweb.org/anthology/Q16-1029},
pages = {401--415},
}
'''

_a	 =     '''\
SARI is a metric used for evaluating automatic text simplification systems.
The metric compares the predicted simplified sentences against the reference
and the source sentences. It explicitly measures the goodness of words that are
added, deleted and kept by the system.
Sari = (F1_add + F1_keep + P_del) / 3
where
F1_add: n-gram F1 score for add operation
F1_keep: n-gram F1 score for keep operation
P_del: n-gram precision score for delete operation
n = 4, as in the original paper.

This implementation is adapted from Tensorflow\'s tensor2tensor implementation [3].
It has two differences with the original GitHub [1] implementation:
  (1) Defines 0/0=1 instead of 0 to give higher scores for predictions that match
      a target exactly.
  (2) Fixes an alleged bug [2] in the keep score computation.
[1] https://github.com/cocoxu/simplification/blob/master/SARI.py
    (commit 0210f15)
[2] https://github.com/cocoxu/simplification/issues/6
[3] https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py
'''


_a	 =     '''
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences.
Args:
    sources: list of source sentences where each sentence should be a string.
    predictions: list of predicted sentences where each sentence should be a string.
    references: list of lists of reference sentences where each sentence should be a string.
Returns:
    sari: sari score
Examples:
    >>> sources=["About 95 species are currently accepted ."]
    >>> predictions=["About 95 you now get in ."]
    >>> references=[["About 95 species are currently known .","About 95 species are now accepted .","95 species are now accepted ."]]
    >>> sari = datasets.load_metric("sari")
    >>> results = sari.compute(sources=sources, predictions=predictions, references=references)
    >>> print(results)
    {\'sari\': 26.953601953601954}
'''







def _a				( SCREAMING_SNAKE_CASE	:    Dict					,      SCREAMING_SNAKE_CASE	:    Optional[Any]					,      SCREAMING_SNAKE_CASE	:    Tuple					,      SCREAMING_SNAKE_CASE	:    Optional[Any]	)					->					Dict:

 """simple docstring"""






 __lowerCAmelCase:     str     			=   [rgram for rgrams in rgramslist for rgram in rgrams]
 __lowerCAmelCase:     List[Any]     			=   Counter(SCREAMING_SNAKE_CASE	)

 __lowerCAmelCase:     List[str]     			=   Counter(SCREAMING_SNAKE_CASE	)
 __lowerCAmelCase:     int     			=   Counter()
 for sgram, scount in sgramcounter.items():
  __lowerCAmelCase:     Optional[int]     			=   scount * numref

 __lowerCAmelCase:     Optional[Any]     			=   Counter(SCREAMING_SNAKE_CASE	)
 __lowerCAmelCase:     Optional[Any]     			=   Counter()
 for cgram, ccount in cgramcounter.items():
  __lowerCAmelCase:     Tuple     			=   ccount * numref

 # KEEP
 __lowerCAmelCase:     int     			=   sgramcounter_rep & cgramcounter_rep
 __lowerCAmelCase:     Union[str, Any]     			=   keepgramcounter_rep & rgramcounter
 __lowerCAmelCase:     Optional[int]     			=   sgramcounter_rep & rgramcounter

 __lowerCAmelCase:     Union[str, Any]     			=   0
 __lowerCAmelCase:     Any     			=   0
 for keepgram in keepgramcountergood_rep:
  keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
  # Fix an alleged bug [2] in the keep score computation.
  # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
  keeptmpscorea += keepgramcountergood_rep[keepgram]
 # Define 0/0=1 instead of 0 to give higher scores for predictions that match
 #      a target exactly.
 __lowerCAmelCase:     Tuple     			=   1
 __lowerCAmelCase:     List[Any]     			=   1
 if len(SCREAMING_SNAKE_CASE	) > 0:
  __lowerCAmelCase:     Tuple     			=   keeptmpscorea / len(SCREAMING_SNAKE_CASE	)
 if len(SCREAMING_SNAKE_CASE	) > 0:
  # Fix an alleged bug [2] in the keep score computation.
  # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
  __lowerCAmelCase:     str     			=   keeptmpscorea / sum(keepgramcounterall_rep.values()	)
 __lowerCAmelCase:     List[str]     			=   0
 if keepscore_precision > 0 or keepscore_recall > 0:
  __lowerCAmelCase:     List[Any]     			=   2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)

 # DELETION
 __lowerCAmelCase:     List[Any]     			=   sgramcounter_rep - cgramcounter_rep
 __lowerCAmelCase:     Optional[Any]     			=   delgramcounter_rep - rgramcounter
 __lowerCAmelCase:     str     			=   sgramcounter_rep - rgramcounter
 __lowerCAmelCase:     int     			=   0
 __lowerCAmelCase:     Optional[int]     			=   0
 for delgram in delgramcountergood_rep:
  deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
  deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
 # Define 0/0=1 instead of 0 to give higher scores for predictions that match
 # a target exactly.
 __lowerCAmelCase:     List[str]     			=   1
 if len(SCREAMING_SNAKE_CASE	) > 0:
  __lowerCAmelCase:     List[Any]     			=   deltmpscorea / len(SCREAMING_SNAKE_CASE	)

 # ADDITION
 __lowerCAmelCase:     Optional[Any]     			=   set(SCREAMING_SNAKE_CASE	) - set(SCREAMING_SNAKE_CASE	)
 __lowerCAmelCase:     int     			=   set(SCREAMING_SNAKE_CASE	) & set(SCREAMING_SNAKE_CASE	)
 __lowerCAmelCase:     Tuple     			=   set(SCREAMING_SNAKE_CASE	) - set(SCREAMING_SNAKE_CASE	)

 __lowerCAmelCase:     Union[str, Any]     			=   0
 for addgram in addgramcountergood:
  addtmpscore += 1

 # Define 0/0=1 instead of 0 to give higher scores for predictions that match
 # a target exactly.
 __lowerCAmelCase:     Optional[Any]     			=   1
 __lowerCAmelCase:     Union[str, Any]     			=   1
 if len(SCREAMING_SNAKE_CASE	) > 0:
  __lowerCAmelCase:     int     			=   addtmpscore / len(SCREAMING_SNAKE_CASE	)
 if len(SCREAMING_SNAKE_CASE	) > 0:
  __lowerCAmelCase:     str     			=   addtmpscore / len(SCREAMING_SNAKE_CASE	)
 __lowerCAmelCase:     Dict     			=   0
 if addscore_precision > 0 or addscore_recall > 0:
  __lowerCAmelCase:     str     			=   2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

 return (keepscore, delscore_precision, addscore)







def _a				( SCREAMING_SNAKE_CASE	:    Optional[int]					,      SCREAMING_SNAKE_CASE	:    List[Any]					,      SCREAMING_SNAKE_CASE	:    Optional[Any]	)					->					List[str]:

 """simple docstring"""






 __lowerCAmelCase:     List[Any]     			=   len(SCREAMING_SNAKE_CASE	)

 __lowerCAmelCase:     int     			=   ssent.split(' '	)
 __lowerCAmelCase:     List[str]     			=   csent.split(' '	)
 __lowerCAmelCase:     Dict     			=   []
 __lowerCAmelCase:     Any     			=   []
 __lowerCAmelCase:     Optional[int]     			=   []
 __lowerCAmelCase:     str     			=   []
 __lowerCAmelCase:     Dict     			=   []
 __lowerCAmelCase:     str     			=   []

 __lowerCAmelCase:     str     			=   []
 __lowerCAmelCase:     Dict     			=   []
 __lowerCAmelCase:     Dict     			=   []
 __lowerCAmelCase:     Optional[Any]     			=   []
 for rsent in rsents:
  __lowerCAmelCase:     List[Any]     			=   rsent.split(' '	)
  __lowerCAmelCase:     Optional[int]     			=   []
  __lowerCAmelCase:     List[str]     			=   []
  __lowerCAmelCase:     Optional[int]     			=   []
  ragramslist.append(SCREAMING_SNAKE_CASE	)
  for i in range(0					,      len(SCREAMING_SNAKE_CASE	) - 1	):
   if i < len(SCREAMING_SNAKE_CASE	) - 1:
    __lowerCAmelCase:     List[str]     			=   ragrams[i] + ' ' + ragrams[i + 1]
    ragrams.append(SCREAMING_SNAKE_CASE	)
   if i < len(SCREAMING_SNAKE_CASE	) - 2:
    __lowerCAmelCase:     Union[str, Any]     			=   ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2]
    ragrams.append(SCREAMING_SNAKE_CASE	)
   if i < len(SCREAMING_SNAKE_CASE	) - 3:
    __lowerCAmelCase:     Optional[int]     			=   ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3]
    ragrams.append(SCREAMING_SNAKE_CASE	)
  ragramslist.append(SCREAMING_SNAKE_CASE	)
  ragramslist.append(SCREAMING_SNAKE_CASE	)
  ragramslist.append(SCREAMING_SNAKE_CASE	)

 for i in range(0					,      len(SCREAMING_SNAKE_CASE	) - 1	):
  if i < len(SCREAMING_SNAKE_CASE	) - 1:
   __lowerCAmelCase:     Optional[int]     			=   sagrams[i] + ' ' + sagrams[i + 1]
   sagrams.append(SCREAMING_SNAKE_CASE	)
  if i < len(SCREAMING_SNAKE_CASE	) - 2:
   __lowerCAmelCase:     Any     			=   sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2]
   sagrams.append(SCREAMING_SNAKE_CASE	)
  if i < len(SCREAMING_SNAKE_CASE	) - 3:
   __lowerCAmelCase:     Optional[int]     			=   sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3]
   sagrams.append(SCREAMING_SNAKE_CASE	)

 for i in range(0					,      len(SCREAMING_SNAKE_CASE	) - 1	):
  if i < len(SCREAMING_SNAKE_CASE	) - 1:
   __lowerCAmelCase:     Optional[int]     			=   cagrams[i] + ' ' + cagrams[i + 1]
   cagrams.append(SCREAMING_SNAKE_CASE	)
  if i < len(SCREAMING_SNAKE_CASE	) - 2:
   __lowerCAmelCase:     str     			=   cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2]
   cagrams.append(SCREAMING_SNAKE_CASE	)
  if i < len(SCREAMING_SNAKE_CASE	) - 3:
   __lowerCAmelCase:     str     			=   cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3]
   cagrams.append(SCREAMING_SNAKE_CASE	)

 ((__lowerCAmelCase)			,							(__lowerCAmelCase)			,							(__lowerCAmelCase)):     Union[str, Any]     			=   SARIngram(SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE	)
 ((__lowerCAmelCase)			,							(__lowerCAmelCase)			,							(__lowerCAmelCase)):     str     			=   SARIngram(SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE	)
 ((__lowerCAmelCase)			,							(__lowerCAmelCase)			,							(__lowerCAmelCase)):     Union[str, Any]     			=   SARIngram(SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE	)
 ((__lowerCAmelCase)			,							(__lowerCAmelCase)			,							(__lowerCAmelCase)):     Tuple     			=   SARIngram(SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE					,      SCREAMING_SNAKE_CASE	)
 __lowerCAmelCase:     List[Any]     			=   sum([keepascore, keepascore, keepascore, keepascore]	) / 4
 __lowerCAmelCase:     Any     			=   sum([delascore, delascore, delascore, delascore]	) / 4
 __lowerCAmelCase:     Any     			=   sum([addascore, addascore, addascore, addascore]	) / 4
 __lowerCAmelCase:     List[Any]     			=   (avgkeepscore + avgdelscore + avgaddscore) / 3
 return finalscore







def _a				( SCREAMING_SNAKE_CASE	:    int					,      SCREAMING_SNAKE_CASE	:    bool = True					,      SCREAMING_SNAKE_CASE	:    str = "13a"					,      SCREAMING_SNAKE_CASE	:    bool = True	)					->					Optional[Any]:

 """simple docstring"""






 if lowercase:
  __lowerCAmelCase:     str     			=   sentence.lower()

 if tokenizer in ["13a", "intl"]:
  if version.parse(sacrebleu.__version__	).major >= 2:
   __lowerCAmelCase:     Dict     			=   sacrebleu.metrics.bleu._get_tokenizer(SCREAMING_SNAKE_CASE	)()(SCREAMING_SNAKE_CASE	)
  else:
   __lowerCAmelCase:     str     			=   sacrebleu.TOKENIZERS[tokenizer]()(SCREAMING_SNAKE_CASE	)
 elif tokenizer == "moses":
  __lowerCAmelCase:     Optional[int]     			=   sacremoses.MosesTokenizer().tokenize(SCREAMING_SNAKE_CASE					,      return_str=SCREAMING_SNAKE_CASE					,      escape=SCREAMING_SNAKE_CASE	)
 elif tokenizer == "penn":
  __lowerCAmelCase:     List[str]     			=   sacremoses.MosesTokenizer().penn_tokenize(SCREAMING_SNAKE_CASE					,      return_str=SCREAMING_SNAKE_CASE	)
 else:
  __lowerCAmelCase:     Any     			=   sentence

 if not return_str:
  __lowerCAmelCase:     List[Any]     			=   normalized_sent.split()

 return normalized_sent






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,			_KWARGS_DESCRIPTION      )
class 							A_				(	datasets.Metric      ):


     def 						UpperCAmelCase						(							self    :	int      )							->			Tuple:
      return datasets.MetricInfo(
          description=_DESCRIPTION    ,						citation=_CITATION    ,						inputs_description=_KWARGS_DESCRIPTION    ,						features=datasets.Features(
              {
                  'sources': datasets.Value('string'    ,						id='sequence'      ),
                  'predictions': datasets.Value('string'    ,						id='sequence'      ),
                  'references': datasets.Sequence(datasets.Value('string'    ,						id='sequence'      )    ,						id='references'      ),
              }      )    ,						codebase_urls=[
              'https://github.com/cocoxu/simplification/blob/master/SARI.py',
              'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py',
          ]    ,						reference_urls=['https://www.aclweb.org/anthology/Q16-1029.pdf']    ,						)


     def 						UpperCAmelCase						(							self    :	Any    ,						UpperCAmelCase    :	List[Any]    ,						UpperCAmelCase    :	List[str]    ,						UpperCAmelCase    :	int      )							->			Optional[Any]:
      if not (len(UpperCAmelCase      ) == len(UpperCAmelCase      ) == len(UpperCAmelCase      )):
       raise ValueError('Sources length must match predictions and references lengths.'      )
      __lowerCAmelCase:     Optional[int]     			=   0
      for src, pred, refs in zip(UpperCAmelCase    ,						UpperCAmelCase    ,						UpperCAmelCase      ):
       sari_score += SARIsent(normalize(UpperCAmelCase      )    ,						normalize(UpperCAmelCase      )    ,						[normalize(UpperCAmelCase      ) for sent in refs]      )
      __lowerCAmelCase:     int     			=   sari_score / len(UpperCAmelCase      )
      return {"sari": 1_0_0 * sari_score}





