



'''simple docstring'''






import datasets

from .evaluate import evaluate


lowerCAmelCase: List[Any]							=						'\\n@article{hendrycks2021cuad,\n      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n      journal={arXiv preprint arXiv:2103.06268},\n      year={2021}\n}\n'

lowerCAmelCase: int							=						'\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n'

lowerCAmelCase: str							=						'\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair as given in the references (see below)\n        - \'prediction_text\': list of possible texts for the answer, as a list of strings\n        depending on a threshold on the confidence probability of each prediction.\n    references: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair (see above),\n        - \'answers\': a Dict in the CUAD dataset format\n            {\n                \'text\': list of possible texts for the answer, as a list of strings\n                \'answer_start\': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\n    \'aupr\': Area Under the Precision-Recall curve\n    \'prec_at_80_recall\': Precision at 80% recall\n    \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n    >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n    >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n    >>> cuad_metric = datasets.load_metric("cuad")\n    >>> results = cuad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n'

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







    def       lowercase_	(				self			:  List[Any]     ):
      return datasets.MetricInfo(
          description=_DESCRIPTION						,      citation=_CITATION						,      inputs_description=_KWARGS_DESCRIPTION						,      features=datasets.Features(
              {
                  'predictions': {
                      'id': datasets.Value('string'     ),
                      'prediction_text': datasets.features.Sequence(datasets.Value('string'     )     ),
                  },
                  'references': {
                      'id': datasets.Value('string'     ),
                      'answers': datasets.features.Sequence(
                          {
                              'text': datasets.Value('string'     ),
                              'answer_start': datasets.Value('int32'     ),
                          }     ),
                  },
              }     )						,      codebase_urls=['https://www.atticusprojectai.org/cuad']						,      reference_urls=['https://www.atticusprojectai.org/cuad']						,      )







    def       lowercase_	(				self			:  int						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  Dict     ):
      a						: Optional[int]					       =					{prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
      a						: Dict					       =					[
          {
              '''paragraphs''': [
                  {
                      '''qas''': [
                          {
                              '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
                              '''id''': ref['''id'''],
                          }
                          for ref in references
                      ]
                  }
              ]
          }
      ]
      a						: Union[str, Any]					       =					evaluate(dataset=_a						,      predictions=_a     )
      return score





'''simple docstring'''






import unittest

from transformers import MraConfig, is_torch_available
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


if is_torch_available():
     import torch

     from transformers import (
         MraForMaskedLM,
         MraForMultipleChoice,
         MraForQuestionAnswering,
         MraForSequenceClassification,
         MraForTokenClassification,
         MraModel,
     )
     from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST

class 							a__:







    def __init__(				self			:  Union[str, Any]						,      __snake_case			:  Optional[int]						,      __snake_case			:  Optional[int]=2						,      __snake_case			:  Union[str, Any]=8						,      __snake_case			:  List[str]=True						,      __snake_case			:  Dict=True						,      __snake_case			:  Optional[Any]=True						,      __snake_case			:  List[str]=True						,      __snake_case			:  Tuple=99						,      __snake_case			:  int=16						,      __snake_case			:  Optional[int]=5						,      __snake_case			:  int=2						,      __snake_case			:  Tuple=36						,      __snake_case			:  Optional[Any]="gelu"						,      __snake_case			:  str=0.0						,      __snake_case			:  Optional[int]=0.0						,      __snake_case			:  Tuple=5_12						,      __snake_case			:  str=16						,      __snake_case			:  str=2						,      __snake_case			:  int=0.02						,      __snake_case			:  Optional[int]=3						,      __snake_case			:  List[Any]=4						,      __snake_case			:  Any=None						,      ):
      a						: int					       =					parent
      a						: Any					       =					batch_size
      a						: Optional[int]					       =					seq_length
      a						: List[str]					       =					is_training
      a						: Dict					       =					use_input_mask
      a						: Union[str, Any]					       =					use_token_type_ids
      a						: Tuple					       =					use_labels
      a						: Dict					       =					vocab_size
      a						: Optional[int]					       =					hidden_size
      a						: List[Any]					       =					num_hidden_layers
      a						: Optional[Any]					       =					num_attention_heads
      a						: str					       =					intermediate_size
      a						: Dict					       =					hidden_act
      a						: str					       =					hidden_dropout_prob
      a						: Tuple					       =					attention_probs_dropout_prob
      a						: Optional[Any]					       =					max_position_embeddings
      a						: Tuple					       =					type_vocab_size
      a						: int					       =					type_sequence_label_size
      a						: List[Any]					       =					initializer_range
      a						: List[str]					       =					num_labels
      a						: List[str]					       =					num_choices
      a						: Optional[Any]					       =					scope







    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: List[Any]					       =					ids_tensor([self.batch_size, self.seq_length]						,      self.vocab_size     )

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

      a						: Tuple					       =					None
      if self.use_token_type_ids:
        a						: Optional[Any]					       =					ids_tensor([self.batch_size, self.seq_length]						,      self.type_vocab_size     )

      a						: str					       =					None
      a						: int					       =					None
      a						: Any					       =					None
      if self.use_labels:
        a						: int					       =					ids_tensor([self.batch_size]						,      self.type_sequence_label_size     )
        a						: Union[str, Any]					       =					ids_tensor([self.batch_size, self.seq_length]						,      self.num_labels     )
        a						: List[str]					       =					ids_tensor([self.batch_size]						,      self.num_choices     )

      a						: Dict					       =					self.get_config()

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







    def       lowercase_	(				self			:  Union[str, Any]     ):
      return MraConfig(
          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=__snake_case						,      initializer_range=self.initializer_range						,      )







    def       lowercase_	(				self			:  List[str]     ):
      a						: List[Any]					       =					self.get_config()
      a						: Optional[Any]					       =					3_00
      return config







    def       lowercase_	(				self			:  Union[str, Any]     ):
      (
          (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     
      )						: Optional[Any]					       =					self.prepare_config_and_inputs()

      a						: Union[str, Any]					       =					True
      a						: Tuple					       =					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
      a						: Dict					       =					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       lowercase_	(				self			:  int						,      __snake_case			:  int						,      __snake_case			:  List[Any]						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  List[Any]						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  Dict						,      __snake_case			:  Any     ):
      a						: Dict					       =					MraModel(config=__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: str					       =					model(__snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case     )
      a						: List[str]					       =					model(__snake_case						,      token_type_ids=__snake_case     )
      a						: Union[str, Any]					       =					model(__snake_case     )
      self.parent.assertEqual(result.last_hidden_state.shape						,      (self.batch_size, self.seq_length, self.hidden_size)     )







    def       lowercase_	(				self			:  List[str]						,      __snake_case			:  Tuple						,      __snake_case			:  List[str]						,      __snake_case			:  str						,      __snake_case			:  Optional[Any]						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  Any						,      __snake_case			:  Optional[Any]						,      __snake_case			:  Optional[int]						,      __snake_case			:  List[Any]						,      ):
      a						: Optional[Any]					       =					True
      a						: Optional[int]					       =					MraModel(__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: List[Any]					       =					model(
          __snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      encoder_hidden_states=__snake_case						,      encoder_attention_mask=__snake_case						,      )
      a						: Any					       =					model(
          __snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      encoder_hidden_states=__snake_case						,      )
      a						: Optional[int]					       =					model(__snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case     )
      self.parent.assertEqual(result.last_hidden_state.shape						,      (self.batch_size, self.seq_length, self.hidden_size)     )







    def       lowercase_	(				self			:  Optional[Any]						,      __snake_case			:  int						,      __snake_case			:  List[Any]						,      __snake_case			:  Optional[int]						,      __snake_case			:  Optional[Any]						,      __snake_case			:  List[Any]						,      __snake_case			:  Dict						,      __snake_case			:  Optional[Any]     ):
      a						: Union[str, Any]					       =					MraForMaskedLM(config=__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: List[str]					       =					model(__snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      labels=__snake_case     )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.seq_length, self.vocab_size)     )







    def       lowercase_	(				self			:  Tuple						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  str						,      __snake_case			:  Tuple						,      __snake_case			:  str						,      __snake_case			:  Tuple						,      __snake_case			:  Optional[int]						,      __snake_case			:  int     ):
      a						: Optional[int]					       =					MraForQuestionAnswering(config=__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: Optional[int]					       =					model(
          __snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      start_positions=__snake_case						,      end_positions=__snake_case						,      )
      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       lowercase_	(				self			:  Dict						,      __snake_case			:  Tuple						,      __snake_case			:  List[Any]						,      __snake_case			:  List[Any]						,      __snake_case			:  Optional[Any]						,      __snake_case			:  Any						,      __snake_case			:  List[str]						,      __snake_case			:  str     ):
      a						: Tuple					       =					self.num_labels
      a						: Dict					       =					MraForSequenceClassification(__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: Any					       =					model(__snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      labels=__snake_case     )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.num_labels)     )







    def       lowercase_	(				self			:  str						,      __snake_case			:  Dict						,      __snake_case			:  Optional[Any]						,      __snake_case			:  int						,      __snake_case			:  List[Any]						,      __snake_case			:  Any						,      __snake_case			:  List[Any]						,      __snake_case			:  int     ):
      a						: Tuple					       =					self.num_labels
      a						: Tuple					       =					MraForTokenClassification(config=__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: List[Any]					       =					model(__snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      labels=__snake_case     )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.seq_length, self.num_labels)     )







    def       lowercase_	(				self			:  Any						,      __snake_case			:  Any						,      __snake_case			:  str						,      __snake_case			:  Dict						,      __snake_case			:  List[Any]						,      __snake_case			:  Any						,      __snake_case			:  Any						,      __snake_case			:  str     ):
      a						: Optional[int]					       =					self.num_choices
      a						: int					       =					MraForMultipleChoice(config=__snake_case     )
      model.to(__snake_case     )
      model.eval()
      a						: Tuple					       =					input_ids.unsqueeze(1     ).expand(-1						,      self.num_choices						,      -1     ).contiguous()
      a						: Optional[int]					       =					token_type_ids.unsqueeze(1     ).expand(-1						,      self.num_choices						,      -1     ).contiguous()
      a						: Optional[Any]					       =					input_mask.unsqueeze(1     ).expand(-1						,      self.num_choices						,      -1     ).contiguous()
      a						: int					       =					model(
          __snake_case						,      attention_mask=__snake_case						,      token_type_ids=__snake_case						,      labels=__snake_case						,      )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.num_choices)     )







    def       lowercase_	(				self			:  Optional[Any]     ):
      a						: Union[str, Any]					       =					self.prepare_config_and_inputs()
      (
          (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     (
          a
      )       ,     
      )						: Union[str, Any]					       =					config_and_inputs
      a						: List[str]					       =					{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
      return config, inputs_dict

@require_torch
class 							a__( lowerCamelCase__		,			unittest.TestCase     ):
    lowercase__			=   (
        (
            MraModel,
            MraForMaskedLM,
            MraForMultipleChoice,
            MraForQuestionAnswering,
            MraForSequenceClassification,
            MraForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    lowercase__			=   False
    lowercase__			=   False
    lowercase__			=   False
    lowercase__			=   False

    lowercase__			=   ()







    def       lowercase_	(				self			:  Any     ):
      a						: Tuple					       =					MraModelTester(self     )
      a						: str					       =					ConfigTester(self						,      config_class=__snake_case						,      hidden_size=37     )







    def       lowercase_	(				self			:  List[str]     ):
      self.config_tester.run_common_tests()







    def       lowercase_	(				self			:  List[str]     ):
      a						: List[Any]					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__snake_case     )







    def       lowercase_	(				self			:  Any     ):
      a						: Union[str, Any]					       =					self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
        a						: Dict					       =					type
        self.model_tester.create_and_check_model(*__snake_case     )







    def       lowercase_	(				self			:  List[Any]     ):
      a						: Dict					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*__snake_case     )







    def       lowercase_	(				self			:  Optional[Any]     ):
      a						: List[str]					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_multiple_choice(*__snake_case     )







    def       lowercase_	(				self			:  List[Any]     ):
      a						: int					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*__snake_case     )







    def       lowercase_	(				self			:  Tuple     ):
      a						: Tuple					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*__snake_case     )







    def       lowercase_	(				self			:  Optional[Any]     ):
      a						: Dict					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*__snake_case     )







    @slow
    def       lowercase_	(				self			:  int     ):
      for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						: Dict					       =					MraModel.from_pretrained(__snake_case     )
        self.assertIsNotNone(__snake_case     )







    @unittest.skip(reason='MRA does not output attentions'     )
    def       lowercase_	(				self			:  Union[str, Any]     ):
      return

@require_torch
class 							a__( unittest.TestCase     ):







    @slow
    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: Union[str, Any]					       =					MraModel.from_pretrained('uw-madison/mra-base-512-4'     )
      a						: List[str]					       =					torch.arange(2_56     ).unsqueeze(0     )

      with torch.no_grad():
        a						: Optional[int]					       =					model(__snake_case     )[0]

      a						: Any					       =					torch.Size((1, 2_56, 7_68)     )
      self.assertEqual(output.shape						,      __snake_case     )

      a						: str					       =					torch.tensor(
          [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]]     )

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







    @slow
    def       lowercase_	(				self			:  Optional[int]     ):
      a						: Dict					       =					MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4'     )
      a						: Optional[int]					       =					torch.arange(2_56     ).unsqueeze(0     )

      with torch.no_grad():
        a						: Dict					       =					model(__snake_case     )[0]

      a						: Union[str, Any]					       =					5_02_65

      a						: Dict					       =					torch.Size((1, 2_56, vocab_size)     )
      self.assertEqual(output.shape						,      __snake_case     )

      a						: Dict					       =					torch.tensor(
          [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]]     )

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







    @slow
    def       lowercase_	(				self			:  Any     ):
      a						: Dict					       =					MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3'     )
      a						: Optional[int]					       =					torch.arange(40_96     ).unsqueeze(0     )

      with torch.no_grad():
        a						: Tuple					       =					model(__snake_case     )[0]

      a						: List[Any]					       =					5_02_65

      a						: str					       =					torch.Size((1, 40_96, vocab_size)     )
      self.assertEqual(output.shape						,      __snake_case     )

      a						: int					       =					torch.tensor(
          [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]]     )

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